Environment Variables in Next.js


Uncategorized

Updated Aug 11th, 2021

Since version 9.4+ (May 2020) we no longer use a “next.config.js” file for environment variables. Thank good ness because the code below, although simple, is a bit wonky.

// In next.config.js file


const { PHASE_DEVELOPMENT_SERVER } = require("next/constants")

module.exports = phase => {
  if (phase === PHASE_DEVELOPMENT_SERVER) {
    return {
      env: {
        BASEURL: "http://localhost:8080"
      }
    }
  }

  return {
    env: {
      BASEURL: "https://backendquotes.herokuapp.com"
    }
  }
}

There are so many types of a “.env” now, it is almost too much choice.

// Okay to put secrets in here...
.env.local
.env.development.local
.env.production.local


// Do not put secrets in here!!!
.env.local
.env.development.local
.env.production.local

There are also testing versions

To expose a variable to the front-end (example: analytics) use the “NEXT_PUBLIC_” prefix.

Note: do not put environment variables in quotes.