Next.js: Environment variables

If you’ve ever used create-react-app, you may have needed to use environment variables, say for setting the URL of an API server. Fortunately, it makes it really easy.

Using environment variables in create-react-app

First, create a .env file in your project. Then, add each environment variable with the prefix REACT_APP_ to this file. The prefix allow create-react-app to whitelist them as being safe to bring into your app.

An example .env file would look like:

REACT_APP_API_URL = http://localhost:7000
REACT_APP_OTHER_THING = important_value

We can then use the variable in JavaScript by accessing it from process.env:

const apiURL = process.env.REACT_APP_API_URL

With Next.js, it’s currently not so easy. However, it is possible with a little Webpack mojo!

Using environment variables in Next.js

First, create the .env file and add the environment variables as just before. An example .env file would be:

API_URL = http://localhost:7000
OTHER_THING = important_value

First, install the dotenv package to load this file in. This is something create-react-app does for us.

npm i dotenv --save
# or if using yarn:
yarn add dotenv

If you don’t current have one, create a next.config.js file in your Next project directory. Here we can hook into the Webpack configuration and customize it to our will.

First, load the dotenv package with its default config of using a file named .env. This will get the variables available for server rendering. Then, use the EnvironmentPlugin class to use the loaded environment variables in the front-end JavaScript that Webpack generates.

require('dotenv').config()
const webpack = require('webpack')
module.exports = {
webpack: (config) => {
config.plugins.push(
new webpack.EnvironmentPlugin(process.env)
)
    return config
}
}

Whitelisting our env variables

You might notice that this allows any environment variable to be available to Webpack. If you want to lock this down, we can use the result of dotenv’s .config() method like so:

const { parsed: localEnv } = require('dotenv').config()
const webpack = require('webpack')
module.exports = {
webpack: (config) => {
config.plugins.push(
new webpack.EnvironmentPlugin(localEnv)
)
    return config
}
}

I’ve created a create-next Node package. It makes the above config file creation a one liner:

yarn create next env
# or if using npm:
npm i create-next --save-dev
create-next env
One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.