Hazem
Hazem

Reputation: 53

Env vars are undefined in Nextjs v12.0.8

I created a .env.local file and tried to console process.env.TEST (test env var) but I'm getting undefined. It seems process.env is always empty. I restarted the server but I still don't see the env vars. I even tried to start a new empty project and process.env is still empty.

Am I missing something? All the other posts I see seem to have figured it out but I still can't. My .env.local file is on the root level. I also tried to append the var with NEXT_PUBLIC, but that didn't help.

Upvotes: 1

Views: 6956

Answers (1)

Mentlegen
Mentlegen

Reputation: 1278

By convention, React env variables must be prefixed with REACT_APP_ in order to be used with process.env. In the case of Next.js, you can put them in the .env.local, but they would only be available in the Node.js environment. If you need to make them available in the browser, you need to prefix them with NEXT_PUBLIC_. Refer to the documentation for more details.

Another way (more old school Next.js) would be to have a next.config.js file. A possible config would be:

const conf = {
  env: {
    myVar: process.env.MY_VAR,
  },
};

module.exports = conf;

Then you could simply use process.env.myVar inside your code. See this page for more information.

Upvotes: 3

Related Questions