Handle environment configuration in Next.js > 9

Ismael Bakkali
guidesmiths
Published in
2 min readJul 17, 2020

We all know how important is loading different configuration on each environment. Unfortunately, on Nextjs it may be seen limited and confused. To be honest, I couldn’t find a proper way to handle it. It turns out is common problem https://github.com/vercel/next.js/discussions/12077. And that’s the why of the post.

There is a way I’ve been using with a positive outcome. Basically, using one package https://www.npmjs.com/package/config. From its doc:

It lets you define a set of default parameters, and extend 
them for different deployment environments (development, qa,
staging, production, etc.).

Let’s gets hands on

After installing the package. You’ll need to create a folder config on the root, with all environment stages you’d like to have.

On the default.js (which it’s the base one) you could add the initial configuration model like so:

// default.jsmodule.exports = {
API: {
API_URL: process.env.API_URL || '<http://localhost:4000>',
ENDPOINT: '********',
IS_MOCKING_ENABLED: false,
},
}

Then, to make your config available on both server and client we need to add it to publicRuntimeConfig. If you’d like to have it just on the server side use just serverRuntimeConfig key. You’ll need to create/update next.config.js. Here’s an example.

// next.config.jsconst config = require('config')
const APIConfig = config.get('API')
const nextConfig = {
publicRuntimeConfig: {
APIConfig,
},
}
module.exports = nextConfig

Usage

// anyFile.jsimport getConfig from 'next/config'const { publicRuntimeConfig } = getConfig()const APIConfig = publicRuntimeConfig.APIConfig[...]

Finally, on the package.json you can inject the environment variables to override your app’s configuration.

"start:local": "NODE_ENV=development run-p dev"

That’s all. I hope it helps :)

--

--