Environment Variables

Since the release of Next.js 9.4 we now have a more intuitive and ergonomic experience for adding environment variables. Give it a try!

Examples

To add environment variables to the JavaScript bundle, open next.config.js and add the env config:

  1. module.exports = {
  2. env: {
  3. customKey: 'my-value',
  4. },
  5. }

Now you can access process.env.customKey in your code. For example:

  1. function Page() {
  2. return <h1>The value of customKey is: {process.env.customKey}</h1>
  3. }
  4. export default Page

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.

For example, the following line:

  1. return <h1>The value of customKey is: {process.env.customKey}</h1>

Will end up being:

  1. return <h1>The value of customKey is: {'my-value'}</h1>

Related

[

Introduction to next.config.js

Learn more about the configuration file used by Next.js.]($0b4bd5a3a6817758.md)

[

Built-in support for Environment Variables

Learn more about the new support for environment variables.]($6b1439e11d92dd8e.md)