Search code examples
node.jsnext.jsenvironment-variables

Can't read environment variables from Nextjs project


EDIT:

If you're naming the env correctly in a Dockerfile but it's still not working, you need to set it BEFORE building the project.


I'm having trouble setting and reading environment variables in a NextJS project.

I have two console logs:

console.log('env', process.env.NODE_ENV);
console.log('backend url', process.env.BACKEND_URL);

Running the code without doing anything returns what I expected:

env development
backend url undefined

Exporting variables like this:

NODE_ENV=production
BACKEND_URL=url

Not only prints the previous values, but it also shows the following message in the console:

⚠ You are using a non-standard "NODE_ENV" value in your environment. This creates inconsistencies in the project and is strongly advised against. Read more: https://nextjs.org/docs/messages/non-standard-node-env

Exporting like this:

export NODE_ENV=production
export BACKEND_URL=url

Also prints the same, including the warning.

Running NodeJS like this:

BACKEND_URL=url NODE_ENV=production npm run dev 

Prints the same. echoing the vars prints the correct values.

It's not just the console.logs, I try to use these values in other parts of the code and they act as if these values are still development and undefined.

I have also tried with a .env file:

NODE_ENV=production
BACKEND_URL=url

I can see that it's being read because, when I start the NextJS server, I see the following:

next dev -p 8080

▲ Next.js 14.1.4
- Local:        http://localhost:8080
- Environments: .env

When the file doesn't exist, the line where it says Environment: .env doesn't appear.

Finally, I have checked ~/.bashrc and ~/.zshrc, and they don't have any mentions of NODE_ENV or BACKEND_URL.

What could be happening?


Solution

  • If you're calling out the env variables on the frontend (I assume so), you have to add NEXT_PUBLIC_ prefix on the variables.

    Check more info on their official doc here - https://nextjs.org/docs/app/building-your-application/configuring/environment-variables#bundling-environment-variables-for-the-browser