Logo

dev-resources.site

for different kinds of informations.

Fixing the Stripe API Key Error When Migrating Next.js from Vercel to Azure Static Web Apps

Published at
9/17/2024
Categories
azure
vercel
nextjs
stripe
Author
rajeshkumaryadavdotcom
Categories
4 categories in total
azure
open
vercel
open
nextjs
open
stripe
open
Author
22 person written this
rajeshkumaryadavdotcom
open
Fixing the Stripe API Key Error When Migrating Next.js from Vercel to Azure Static Web Apps

Migrating a Next.js application from one hosting platform to another can introduce unexpected challenges, especially when dealing with environment variables and build processes. Recently, I encountered an issue when moving a Next.js app from Vercel to Azure Static Web Apps. The app utilized Stripe for payment processing, and the migration led to an error:

Uncaught (in promise) IntegrationError: Missing value for Stripe(): apiKey should be a string.
Enter fullscreen mode Exit fullscreen mode

In this blog post, I'll explain why this error occurs and provide a step-by-step solution to resolve it.

Understanding the Error

The error message:

IntegrationError: Missing value for Stripe(): apiKey should be a string.
Enter fullscreen mode Exit fullscreen mode

This error indicates that the loadStripe function is not receiving the required Stripe public API key. In a Next.js application, this typically means that the environment variable NEXT_PUBLIC_STRIPE_PUBLIC_KEY is undefined at runtime.

Environment Variables in Next.js

In Next.js, environment variables are handled differently based on where they are used:

Client-side (Browser) Code: Environment variables must be prefixed with NEXT_PUBLIC_ to be accessible.
Server-side Code: Variables without the NEXT_PUBLIC_ prefix are only available on the server.
During the build process, Next.js replaces process.env.NEXT_PUBLIC_* variables with their actual values.

The Difference Between Vercel and Azure Static Web Apps

Vercel: Automatically injects environment variables into the build and runtime environments.
Azure Static Web Apps: Uses GitHub Actions for the build process, which requires explicit passing of environment variables during the build.
When migrating from Vercel to Azure, environment variables needed during the build (especially for client-side code) must be provided to the GitHub Actions workflow.

Solution Overview

To resolve the error, we need to:

  1. Provide the Stripe public key during the build process by adding it as a secret in GitHub and referencing it in the GitHub Actions workflow.
  2. Set the Stripe secret key for server-side use in Azure Static Web Apps Application Settings.

Step-by-Step Guide to Fix the Error

  1. Add Stripe Public Key as a GitHub Secret Why? The public key is required during the build process to replace process.env.NEXT_PUBLIC_STRIPE_PUBLIC_KEY in the client-side code.

How to Do It:

Navigate to Your GitHub Repository:

Go to the repository associated with your Azure Static Web App.
Access Repository Settings:

Click on the "Settings" tab.
Go to Secrets and Variables:

On the left sidebar, select "Secrets and variables" > "Actions".
Add a New Repository Secret:

Click "New repository secret".
Name: NEXT_PUBLIC_STRIPE_PUBLIC_KEY
Value: Your actual Stripe public key (e.g., pk_test_51H...)
Click "Add secret".

2. Modify the GitHub Actions Workflow

Why? To make the public key available during the build process executed by GitHub Actions.

How to Do It:

Locate Your Workflow File:

Usually found at .github/workflows/azure-static-web-apps-.yml.
Edit the Workflow File:

Add an env section under the Build And Deploy step.
Example Modification:

- name: Build And Deploy
  id: builddeploy
  uses: Azure/static-web-apps-deploy@v1
  with:
    azure_static_web_apps_api_token: ${{ secrets.AZURE_STATIC_WEB_APPS_API_TOKEN_XXXX }}
    repo_token: ${{ secrets.GITHUB_TOKEN }}
    action: "upload"
    app_location: "/" # App source code path
    api_location: "" # API source code path - optional
    output_location: "" # Built app content directory - optional
  env:
    NEXT_PUBLIC_STRIPE_PUBLIC_KEY: ${{ secrets.NEXT_PUBLIC_STRIPE_PUBLIC_KEY }}
Enter fullscreen mode Exit fullscreen mode

3. Set Stripe Secret Key in Azure Application Settings

Why? The secret key is used server-side and should not be exposed during the build or in client-side code.

How to Do It:

Navigate to Your Azure Static Web App in the Azure Portal.

Access Configuration:

Select "Configuration" under "Settings" in the left-hand menu.
Add an Application Setting:

Click "Application settings".
Click "New application setting".
Name: STRIPE_SECRET_KEY
Value: Your actual Stripe secret key (e.g., sk_test_51H...)
Click "OK" or "Add".
Save Changes:

Click "Save" at the top.
Restart the Functions (If Necessary):

This ensures the new settings take effect.

Updated Workflow File

Here's the complete updated GitHub Actions workflow file:

name: Azure Static Web Apps CI/CD

on:
  push:
    branches:
      - main
  pull_request:
    types: [opened, synchronize, reopened, closed]
    branches:
      - main

jobs:
  build_and_deploy_job:
    if: github.event_name == 'push' || (github.event_name == 'pull_request' && github.event.action != 'closed')
    runs-on: ubuntu-latest
    name: Build and Deploy Job
    steps:
      - uses: actions/checkout@v3
        with:
          submodules: true
          lfs: false
      - name: Build And Deploy
        id: builddeploy
        uses: Azure/static-web-apps-deploy@v1
        with:
          azure_static_web_apps_api_token: ${{ secrets.AZURE_STATIC_WEB_APPS_API_TOKEN_XXXX }}
          repo_token: ${{ secrets.GITHUB_TOKEN }}
          action: "upload"
          app_location: "/" # App source code path
          api_location: "" # API source code path - optional
          output_location: "" # Built app content directory - optional
        env:
          NEXT_PUBLIC_STRIPE_PUBLIC_KEY: ${{ secrets.NEXT_PUBLIC_STRIPE_PUBLIC_KEY }}

  close_pull_request_job:
    if: github.event_name == 'pull_request' && github.event.action == 'closed'
    runs-on: ubuntu-latest
    name: Close Pull Request Job
    steps:
      - name: Close Pull Request
        id: closepullrequest
        uses: Azure/static-web-apps-deploy@v1
        with:
          azure_static_web_apps_api_token: ${{ secrets.AZURE_STATIC_WEB_APPS_API_TOKEN_XXXX }}
          action: "close"
Enter fullscreen mode Exit fullscreen mode

Testing the Solution

Commit and Push Changes:

This triggers a new build and deployment via GitHub Actions.
Monitor the Workflow:

Go to the "Actions" tab in GitHub.
Ensure the workflow runs successfully.
Verify the Application:

Access your Azure Static Web App.
Test the Stripe functionality to confirm the error is resolved.
Check for Errors:

Open the browser's developer console.
Ensure there are no errors related to Stripe API keys.

Conclusion

By correctly setting environment variables during the build process and runtime, we resolved the Stripe API key error that occurred when migrating from Vercel to Azure Static Web Apps. The key takeaways are:

Client-Side Environment Variables: Must be available during the build process.
Server-Side Secrets: Should be set in the hosting environment's application settings and never exposed in the code or build logs.
Hosting Platform Differences: Understand how your chosen platform handles environment variables and build processes.

https://www.rajeshkumaryadav.com/donation

stripe Article's
30 articles in total
Favicon
Boost Your Shopify Sales in Australia, the US, and Beyond: Accept Various Payment Methods and Currencies with Stripe
Favicon
Boost Your Shopify Sales in Poland, Europe, and Beyond: Accept Various Payment Methods and Currencies with Stripe
Favicon
Is Stripe your only choice for payment gateway in Sharetribe?
Favicon
Stripe Invoice.Upcoming changes: model switching from monthly to yearly
Favicon
Replay failed stripe events via webhook
Favicon
Building a Payment System for Your Flutter App: A Journey with Stripe Connect and Firebase
Favicon
Understanding Laravel Cashier's Core Traits: A Deep Dive
Favicon
Creating Stripe Test Data in Python
Favicon
Simplifying Payments with Pay gem: A Guide to Using Stripe in Rails
Favicon
Comparison of the middleware implementation between Supabase Auth documentation and the nextjs-stripe-supabase.
Favicon
Building a Custom Shipping Calculator with Stripe and Netlify Functions for Multi-Currency (€/$), Quantity, and Location Support
Favicon
🌟Open-source SaaS Starter: React + Firebase + Stripe + i18n
Favicon
Creating a marketplace with Stripe Connect: The onboarding process
Favicon
Stripe Subscription Integration in Node.js [2024 Ultimate Guide]
Favicon
Clerk Update – November 12, 2024
Favicon
Integrating Stripe Payment Intent in NestJS with Webhook Handling
Favicon
How Mocking Against a Public API Endpoints within Blackbird Gets your API in Production Faster
Favicon
How to add Stripe to Astro
Favicon
Designing Idempotent APIs
Favicon
Building E-Commerce Platforms with Next.js and Stripe: A Step-by-Step Guide
Favicon
How to retrieve the Transactions from Stripe
Favicon
Integration with Stripe for Payment Processing on AWS
Favicon
Providing receipts for in-person transactions with Terminal
Favicon
Providing receipts for in-person transactions with Terminal
Favicon
Top 10 Payment Processors for Next.js Applications [2024]
Favicon
Fixing the Stripe API Key Error When Migrating Next.js from Vercel to Azure Static Web Apps
Favicon
Announcing the Release of my Stripe to SevDesk Integration
Favicon
Receive payments easily using Stripe and PHP
Favicon
Integrating Payment Gateways in Next.js 14
Favicon
Experimenting with pricing: Finding the right strategy for growth!

Featured ones: