'Environment Variables in NextJS are Undefined

I am using the next-auth library which requires the use of environment variables as follows:

  Providers.GitHub({
    clientId: process.env.GITHUB_ID,
    clientSecret: process.env.GITHUB_SECRET,
  }),

However, when I test out next-auth it is not working and it seems to me the reason why is because those variables are not loading properly. As such, I did a little test to see if I can access environment variables in my app and the test showed that I cannot.

This is how the test went:

// .env.local (root level)

NEXT_PUBLIC_ENV_LOCAL_VARIABLE="public_variable_from_env_local"

I then add the following code to my site:

  <h2>test one start</h2>
    {process.env.NEXT_PUBLIC_TEST_ONE}
  <h2>test one end</h2>

  <Spacer />

  <h2>test two start</h2>
    {process.env.TEST_TWO}
  <h2>test two end</h2>

In this case, test one start shows up and test one end shows up, but the environmental variable does NOT show up. The same is true for test two start and test two end.

I did a similar test with console.log - namely:

  console.log("test one", process.env.NEXT_PUBLIC_TEST_ONE)
  console.log("test two", process.env.TEST_TWO)

That turns up as follows:

test one undefined
test two undefined

In short, for whatever reason I seem unable to load environment variables in my nextjs app. Not from next-auth, not in the code and not in a console.log. The variables are undefined and I do not know why.

Any ideas?

Thanks.



Solution 1:[1]

Searching the next.js documentation I found this:

// file: next.config.js

module.exports = {
 env: {
    customKey: 'my-value',
 },
}

// Now you can access process.env.customKey 

// For example, the following line:
// return <h1>The value of customKey is: {process.env.customKey}</h1>

// Will end up being:
// return <h1>The value of customKey is: {'my-value'}</h1>

So it seems, if you are using next.js version at or before 9.4 you place env variables into next.config.js

They also include one warning:

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.

If you are using version 9.4+ the documentation says you can use .env.local files and prefix env variables with NEXT_PUBLIC_ to have them exposed in the browser.

Of note with this method is: In order to keep server-only secrets safe, Next.js replaces process.env.* with the correct values at build time. This means that process.env is not a standard JavaScript object, so you’re not able to use object destructuring.

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