Azure Static Web Apps Environment Variable Not Working

Temesgen Zewude 10 Reputation points
2024-11-03T19:46:38.6633333+00:00

I'm deploying a React app with Azure Static Web Apps and have configured environment variables in the Azure Portal under Configuration > Environment variables. However, these variables are not being injected into the app during deployment.

In the deployed app:

  • Logging process.env shows that the expected environment variables are undefined.
  • When referencing these variables directly in index.html for testing, they remain as placeholders (e.g., %VARIABLE_NAME%) instead of being replaced with their actual values, suggesting they aren’t injected during the build.

The environment variables work correctly when I use a .env file locally, so this issue appears specific to the Azure Static Web Apps deployment.

Troubleshooting Steps Taken:

  • Verified that the environment variables are correctly set in the Azure Static Web Apps settings.
  • Ensured that variables have the required prefixes, as per Create React App requirements.
  • Triggered redeployments to rule out potential caching issues.
  • Confirmed that the environment variables are accessible locally with .env.

Additional Details:

  • App Location: Root directory (/)
  • Output Location: build
  • Deployment Method: GitHub Actions

Is anyone else experiencing issues with environment variables not being injected in Azure Static Web Apps, or have any suggestions on resolving this? Any help would be appreciated. Thank you!

Azure Static Web Apps
Azure Static Web Apps
An Azure service that provides streamlined full-stack web app development.
1,056 questions
{count} vote

1 answer

Sort by: Most helpful
  1. Luis Arias 7,851 Reputation points
    2024-11-03T21:18:34.3766667+00:00

    Hello Temesgen,

    If your environment variables aren’t appearing in your deployed Azure Static Web App, it’s because they aren’t injected into the client-side code by default. Here’s how to resolve it:

    1. Use GitHub Secrets in Your Workflow: Set the environment variables as secrets in your GitHub repository and pass them to the build step.
         - name: Build React App with Environment Variables
           env:
             REACT_APP_API_URL: ${{ secrets.REACT_APP_API_URL }}
           run: npm run build
      
    2. Add REACT_APP_ Prefix: Ensure all environment variables start with REACT_APP_ for Create React App to recognize them. (https://create-react-app.dev/docs/adding-custom-environment-variables/)

    This approach embeds the variables at build time, making them available in the app.

    If the information helped address your question, please Accept the answer.

    Luis


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.