Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Server-side environment variables not working in nextjs app on Azure Web App

Tags:

azure

next.js

I have defined my environment variables in .env.local which works great for local development. Next v13.2.4, React v18.2.0, Node v18 LTS.

On Azure, I've created a Variable Group which contains the same key-value pairs. My understanding is that those variables should then be available in the node context, i.e. on the server-side of my nextjs app. However, when I try to access process.env.API_CLIENT_SECRET (for example) it is always undefined.

If I add the process env vars to env in my next.config.js (see below), then the values are defined in my app (server-side), but of course they are also available on the client-side - which I don't want, as I have client id and secret values for my API:

module.exports = {
  reactStrictMode: true,
  output: "standalone",
   env: {
     API_CLIENT_SECRET: process.env.API_CLIENT_SECRET,
   },
}

This also seems to be the old (pre v9) way of doing things.

I know that adding the NEXT_PUBLIC_ prefix makes your envars available client-side.

Am I missing something here? How can I have my env vars available via process.env on the server-side only in nextjs on Azure?

like image 271
David Conlisk Avatar asked Oct 14 '25 09:10

David Conlisk


1 Answers

UPDATE: The missing step here is to add all variables to the App Settings in the Deploy Azure App Service release pipeline step, like this:

Add App Settings

This means that you can then update those values and simply re-release the app, rather than having to rebuild it first using the older solution (below). There is also no need for the pipeline step to create the .env.local file with this solution.

ORIGINAL ANSWER:

After much trial and error I found a solution that works:

  1. Create a variable group in the library for the pipeline in Azure and define all of the variables that are in the .env.local file
  2. Make sure that the pipeline can access the variable group, and make the variables available in the pipeline:
variables:
  - group: EnvironmentVariables-Dev
  1. Add a step to the build pipeline which writes the variable groups to a .env.local file:
steps
  - script: |
      echo "JWT_SECRET=$(JWT_SECRET)" >> .env.local
      # add your own items here
    displayName: "Create .env.local"

(do this before your npm install and build step(s))

Now the deployed site behaves just like the local site does, reading the required envars from the .env.local file into process.env for use in the code, e.g. process.env.JWT_SECRET, and only variables prefixed with NEXT_PUBLIC_ are available in the browser, which is exactly what is required.

like image 191
David Conlisk Avatar answered Oct 17 '25 02:10

David Conlisk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!