Environment variables are an essential part of securing and configuring apps but when working with Next.js, it has some added support and functionality for handling environment variables that you won't find in a typical Node.js app.
Next.js has built-in flow support for loading environment variables. Having a solid understanding of this process will help avoid any security risks and unintended results.
This guide will cover the basic steps for setting environment variables for each environment, including:
How Next.js loads environment variables.
What environments does Next.js support?
Do I need to use third party packages for .env support?
How the environment is set in test mode.
How to run tests using the Next.js recommended way.
This post will quickly help developers understand how to use Next.js environment variables like a pro.
For a quick start guide on Node.js .env file usage, here's a recap on Nodes.js environment variables. Next.js builds on some of the best strategies when loading .env files.
Let's get started.
Next.js Environment variables
Next.js supports the following standard Node.js environments:
development
production
test
Next.js will display a warning message if any environments besides the standard are used.
It's best to stick to the standard environments to avoid introducing any inconsistencies.
Starting different environments
The Next.js runtime will automatically set the NODE_ENV when using the following commands:
JSON
1{
2 "scripts": {
3 "dev": "next dev",
4 "build": "next build",
5 "start": "next start"
6 }
7}
Each command sets the following:
next dev: sets development mode
next build: sets production mode
next start: sets production mode
One thing to note, is that the build step will use production variables.
Next.js will build static and server side rendered resources during the build phase and so it uses production variables to render the production content.
How Next.js loads .env files.
By default, Next.js will look for .env* files in the root of the project.
Built-in loading order for .env
It will use a specific flow order and it will resolve variables in the following locations.
process.env (Any command line vars will take priority)
.env.[NODE_ENV].local (override to .env.local)
.env.local (except for test env)
.env.[NODE_ENV]
.env
Types of .env variable files
Here's some examples of what files it will look for.
Learn how to build a blog using MDX, Markdown, Front Matter and Next.js
May 24, 2024
Stay in the loop
Get the latest articles delivered to your inbox. No spam, unsubscribe anytime.
.env.development
.env.production.local
.env.production
.env.test
How to know which .env files Next.js loads?
When starting up a Next.js app, it will console log all of the environments that it finds including the flow order it will use to resolve variables.
The Next.js runtime will use the first variable it finds in the sequence path and put the resulting values in the process.env object.
This process allows for max flexibility with the ability to override as needed.
Purposes of different .env files.
Here's a general idea of the purposes for each of the different .env files.
This approach has the following benefits:
Allows for default base environment variables to be checked into the repo for other developers to use as a starting point.
A production environment can use .env.production for defaults and add secrets locally in .env.production.local to debug a production environment.
Using local files like .env.local or .env.*.local to override any local setup or secret keys needed.
General tips
Depending on your development process, you may opt to not check any of these files into the repo, however, if you're using this systematic approach it can offer great flexibility.
Example overriding with local
For example, we can set some default values in .env and .env.development files for some database info.
Sets the base setup variables.
.env
Bash
1DB_HOST=127.0.0.1
2DB_PORT=5432
3DB_USER=default
4DB_PASS=
5DB_NAME=default
Set some development standard setup.
.env.development
Bash
1DB_USER=manager
2DB_NAME=nw-stage-db1
A developer can then override and add their secrets using .env.development.local.
.env.development.local
Bash
1DB_USER=admin
2DB_PASS=super-secret
3DB_NAME=nw-stage-db2 # even override the db name for dev
The approach for a production flow is the same with only the NODE_ENV being set to production. This can be useful when a production issue needs to be debugged.
Accessing .env variables in the client
Since environment variables are only available on the server, they cannot be accessed by client code that runs in the Browser. To make them available in the Browser, Next.js uses a prefix.
NEXT_PUBLIC_: Any variable with this prefix will be available in the client environment.
Using the Next.js public prefix
Any variables prefixed, will be bundled and available in the Browser.
Bash
1SERVER_URL=http://localhost:3000
2
3# change to
4
5NEXT_PUBLIC_SERVER_URL=http://localhost:3000
This is useful for defining API and server URLs for fetch calls among other things.
Next.js has built-in support for referencing other variables in the same .env file. Other variables can be referenced using the $.
For example:
Bash
1# Defines a base path uri
2CONTENT_BASE=/resources/media
3
4# Defines sub paths using the $
5AVATARS=$CONTENT_BASE/avatars
6ICONS=$CONTENT_BASE/icons
This is really useful and makes it easy to change many variables with a single base variable.
If you need to use the actual $ character in any value, you can escape it using the backslash \$.
Bash
1DEFAULT_DISCOUNT_AMT=10.00
2USD_DISCOUNT=\$${DEFAULT_DISCOUNT_AMT}
Testing using Next.js .env variables
The last section we need to cover is how to lauch Next.js in test mode properly.
To run tests using Next.js in test mode, we'll need to add a few things.
Install Jest test dependencies
The testing packages are not installed by default and so we'll need to add:
Jest test runner and some helpers.
React Testing Library (RTL).
@types/jest
Bash
1npm install -D jest jest-environment-jsdom @testing-library/react @testing-library/dom @testing-library/jest-dom ts-node @types/jest
2# or
3yarn add -D jest jest-environment-jsdom @testing-library/react @testing-library/dom @testing-library/jest-dom ts-node @types/jest
4# or
5pnpm install -D jest jest-environment-jsdom @testing-library/react @testing-library/dom @testing-library/jest-dom ts-node @types/jest
Once these packages are installed, you can easily run your Jest tests directly.
However, running them this way will not load the expected test environment variables automaticallly.
package.json
JSON
1{
2 "scripts": {
3 "test": "jest test"
4 }
5 }
By running tests using the next test command is the recommended way.
This way Next.js can set everything up and load the test mode environment variables.
package.json
JSON
1{
2 "scripts": {
3 "test": "next test"
4 }
5 }
In order to let Next.js lauch and execute the Jest test runner, we'll need a wrapper to do the job.
Create a Jest test wrapper
Next.js provides a nextJest wrapper for the Jest test runner.
The benefits of using this approach include:
Loads .env and .env.test variables.
Add ignores to .next and node_modules by default.
Sets transform using the Next.js compiler.
Automatically mocks style sheet modules.
Uses next.config.js for config flags to enable SWC transforms.
It will use tsconfig.json config settings for things like path aliases, etc.
Here's how to create a nextJest wrapper. This wrapper sets the project directory for the Jest test runner and allows for any pass through settings for Jest.
The nextJest helper function will set the Next.js runtime details automatically.
To run any tests, call next test. The next runtime will start the Jest test runner and set the environment and config details automatically.
package.json
JSON
1{
2 "scripts": {
3 "test": "next test"
4 }
5}
You can still run npx jest manually if needed, but next test is the recommended way in a Next.js app.
Next.js will pass any Jest args, like filter paths and flags from command line.
Bash
1npm run test /app/page.spec.tsx
2
3# or pnpm
4
5pnpm test /app/pages/*.spec.tsx
In Conclusion
So as you can see, Next.js provides complete environment flow control. You can easilly set environment variables the way you need too, for large or small projects.
A few key takeaways.
By understanding the Next.js environment flow, you can utilize it more confidently.
Keep things simple at first and only add .env files as you need flexibility.
All three environments are fully supported.
I hope this has helped shed some light on Next.js environment variables.