'Next.js 12 ( with react ): Cannot read env variables, process.env is undefined

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



Solution 1:[1]

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.

Solution 2:[2]

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

Solution 3:[3]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Eric Mabo
Solution 3 Balram Singh