Using Next's build-time configuration
@DarrylR already mentioned using next.config.js and
Next's runtime configuration,
but you can also use Next's build-time configuration.
This lets you put the process.env.XXXX right into the code (as shown in step 3 below), and you don't have to import anything. However, if you env variables should be set both when you build locally with Next.js and when you deploy to ZEIT Now, I don't know if you can keep them in just one file using this method (see step 2 below).
The runtime configuration docs suggest you normally want to use build-time configuration:
Warning: Generally you want to use build-time configuration to provide your configuration. The reason for this is that runtime configuration adds rendering / initialization overhead and is incompatible with automatic prerendering.
Steps:
1. Set NODE_ENV for build process
If you deploy using ZEIT Now, you can set the env variables used at build time in now.json:
{
"version": 2,
"build": {
"env": {
"NODE_ENV": "production"
}
}
}
1.2 When running locally (optional)
If you want NODE_ENV to be set when running locally as well, this will not be set by now.json.
However you can set it in other ways, such as:
$ NODE_ENV=production npm run build
or change the build script in package.json to
"build": "NODE_ENV=production next build"
You can of course also set NODE_ENV for other scripts than build if you want that.
2. Make Next inline value of process.env.NODE_ENV
Add this to the next.config.js as described here:
module.exports = {
env: {
NODE_ENV: process.env.NODE_ENV
}
};
3. Use in code
if (process.env.NODE_ENV === "production") {
console.log("In production")
} else {
console.log("Not in production")
}