4

I'm using next.js 12 with a react app.

I have the following .env.local file:

NEXT_PUBLIC_DEVELOPMENT_ENV_VARIABLE="public_development_variable"

I start the dev server and in the browser i do: console.log('###ENV', process.env) and i always get undefined.

In the logs i have this that confirms that the env file was readed: info - Loaded env from /Users/testdash/.env.local

But process.env is always empty

3
  • Does this answer your question? next.js environment variables are undefined (Next.js 10.0.5) Commented Nov 25, 2021 at 22:56
  • Hi, nope. Already tried Commented Nov 25, 2021 at 22:59
  • 1
    You have to reference the environment variable by its full name. Try logging console.log(process.env.NEXT_PUBLIC_DEVELOPMENT_ENV_VARIABLE). Commented Nov 26, 2021 at 23:24

3 Answers 3

7

If you need to share your environment variables with the browser, prefix them with NEXT_PUBLIC_ and it will be accessible at runtime. All other environment variables are replaced with their values.

e.g. NEXT_PUBLIC_ALGOLIA_INDEX

Sign up to request clarification or add additional context in comments.

Comments

2

The docs mention it here: https://nextjs.org/docs/api-reference/next.config.js/environment-variables

Next.js will replace process.env.customKey with 'my-value' at build time. Trying to destructure process.env variables won't work due to the nature of webpack DefinePlugin.

1 Comment

Edited my answer, the method of setting the env variables wasn't important, it's the fact that the variables themselves get replaced with their values at build time.
0

I just use .env instead of .env.local and it works great locally on Digitalocean or Azure (using nextjs 12)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.