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?
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:
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:
variables:
- group: EnvironmentVariables-Dev
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With