Environment variables are values that can be used to modify an application’s behavior to suit the needs and requirements of a specific environment during production. Most frontend frameworks and cloud hosting services have built-in support for configuring and managing environment variables. Next.js is no exception. In this article, we will take a deep dive into environment variables and explore their customization in Next.js.
Jump ahead:
next.config.js
Environment variables are external values that developers define outside of the actual application code. These values can be used to influence the behavior of an application, and they often store sensitive data like API keys. Environment variables consist of name-value pairs like in the example below:
API_KEY=1234 DB_CONN_STRING="http://localhost:3000"
An application can have different requirements when running in development, testing, and production environments. Instead of having different codebases for the same application, where each codebase is tailored towards a specific environment, an application can have a single codebase whose behavior in the different environments is determined using the environment variable settings.
The application can read the environment variable settings and modify its behavior to meet the requirements of that specific environment. This keeps the codebase short, clean, and organized:
process.env.API_KEY; process.env.DB_CONN_STRING;
In a development environment, tools for code formatting, linting, and testing are essential. However these tools are not necessary in the production stage. When working with tools such as npm, setting the value of the built-in NODE_ENV
environment variable to production
will install dependencies that the application needs in production, excluding those needed in the development stage. This behavior is configurable if necessary.
Similarly, during development, you may need to set up a local instance of your database server separate from the production server. You will have to use environment variables to pick the correct database connection string.
Usually, modifying an environment variable modifies the behavior of an application without requiring you to rebuild or redeploy the application. But in frameworks like Next.js, some environment variables are hardcoded in the codebase at build time. You may need to build and redeploy after modifying an environment variable.
You can use environment variables to store the following:
As mentioned earlier, Next.js has built-in support for environment variables. To start using them, you can declare .env.local
at the root of your project directory:
API_KEY=123456789 USERNAME=username PASSWORD=password
Next.js will load the above environment variables into the process.env
object out of the box so that you can access them in the Node.js environment:
export async function getStaticProps() { console.log(process.env.API_KEY); console.log(process.env.USERNAME); console.log(process.env.PASSWORD); }
The above environment variables are only available in the Node.js environment and are referred to as private environment variables. Prefixing the variable name with NEXT_PUBLIC_
turns them into public environment variables:
NEXT_PUBLIC_API_KEY=123456789 NEXT_PUBLIC_USERNAME=username NEXT_PUBLIC_PASSWORD=password
Public environment variables are available both in the browser and Node.js environments. We will explore public and private environment variables later in this article.
In addition to the .env.local
file, Next.js also gives you the flexibility to store constants and default values in .env
, env.development
, and env.production
environment files. These files are not meant for storing secrets but for environment-specific configurations and settings.
As its name suggests, the env.development
file is for environment variables you want to use only in development. In Next.js, you can launch the development server using the next dev
command. The variables you declare in the env.development
file won’t be available in production.
The env.production
file, on the other hand, is for variables that you want to use only in production. The next start
command builds the project and launches the production environment. The variables you declare in the env.production
file won’t be available in the development environment.
The variables you declare in the .env
file will be available in both development and production environments. Be aware that an environment variable that you look up dynamically, such as in the example below, will not be hardcoded into your production build as we just described:
const variableName = 'BASE_URL'; console.log(process.env[variableName]); const envir = process.env; console.log(envir.BASE_URL);
You can use this sample application to try out the examples in this article. Follow the steps below to clone the repository to your machine and experiment with the environment variables this article highlights.
First, clone a sample application. Use git clone
to clone the sample application to your machine. Then, install dependencies by running the npm install
command.
There are several environment variable files at the root of your project directory. In Next.js, you only store secrets in the env.local
file. Because environment variables holding secrets should not be shared, there is a env.local.template
file you can use to create your env.local
file.
To add secrets, create a env.local
file at the root of your project repository and copy the contents of env.local.template
into it. You can add any secrets you don’t want to expose in a version control system in the env.local
file.
Next, you can launch the development server using the npm run dev
command. The environment variables in the .env.development
file are available only in the development environment. On the other hand, you can build the project and launch the production server using the npm run build
and npm run start
commands. The environment variables in the .env.production
file are available only in the production environment.
Now, the environment variables in the .env
file are available in both the development and production environments.
As we introduced earlier, Next.js environment variables can be categorized into public and private environment variables, but they are private by default. Private environment variables are only accessible from the Node.js environment. You can declare private environment variables in any of your .env*
files like so:
ENV_VARIABLE=env_variable
To make an environment variable public, prefix its name with NEXT_PUBLIC_
as in the example below:
NEXT_PUBLIC_ENV_VARIABLE=nex_public_env_variable
At build time, Next.js will access and replace references to the public environment variables with their actual values in the codebase bundled for the browser environment.
Therefore, in the example below, process.env.NEXT_PUBLIC_ENV_VARIABLE
will be replaced in line with the actual value of the environment variable at build time:
<p>{process.env.NEXT_PUBLIC_ENV_VARIABLE}</p>
Public environment variables are mostly used for storing constants or default values that you don’t want to import or declare in multiple files. You can declare such variables once in a .env*
file, as in the example above, and access them from anywhere in your codebase. They are available both in the browser and in Node.js.
The requirements of an application while in development may not be the same as those in production. Therefore, some environment variables may only be required in development, others in production, and some in both environments.
For example, if you declare the environment variables below in the .env.production
file, they will be available only in the production environment:
BASE_URL='http://localhost:3000' NEXT_PUBLIC_BASE_URL='http://localhost:3000'
Regardless of the file in which you declare the above environment variables, the BASE_URL
environment variable will be available in the Node.js environment because it is a private variable. And NEXT_PUBLIC_BASE_URL
will be available in both the browser and Node.js environments because it is a public environment variable.
next.config.js
Next.js offers flexible ways of working with environment variables. You can use the legacy env
property of the next.config.js
file to configure environment variables, or the newer, more intuitive, and ergonomic .env*
files described above.
You can declare the environment variable as a property of the env
object in the next.config.js
file and access it in your codebase as a property of the process.env
object:
module.exports = { env: { BASE_URL: "http://localhost:3000", }, };
Be aware that using the next.config.js
file for your environment variables will inline the values of the variables at build time and bundle them in your frontend code, irrespective of whether you prefix the variable name with NEXT_PUBLIC_
or not:
export const App = () => { return <p>{process.env.BASE_URL}</p> }
Software development across remote, distributed teams requires the use of version control systems such as Git and cloud Git hosting services like GitHub, BitBucket, and GitLab. During development, certain secrets such as API endpoints, usernames, passwords, API keys, database connection strings, and other credentials that are specific to your local development environment must not be exposed.
In Next.js, you can securely store secrets in the env.local
file. You can add the .env.local
file to your .gitignore
file to avoid checking it into a version control system like Git and pushing it to a cloud Git hosting service like GitHub. Do not store secrets in other environment variables that are not meant for storing secrets.
Checking environment variables to a version control system may result in incurring significant costs if unknown individuals get access to your API keys or production database connection string.
You can share a template of the env.local
file and its contents in a .env.local.example
or .env.local.template
file so that project contributors can set up their development environment using the file template.
Next.js will evaluate all references to environment variables and hardcode them in your client code at build time. After that, all the evaluated values won’t respond to changes in the environment variable.
If your frontend application needs access to dynamic environment variables at runtime, you should set up your own API and provide the variables to your client code.
Similarly, dynamically looking up or destructuring environment variables in your frontend code, as in the example below, won’t work. The value of the environment value will be undefined
. Always access your environment variables using process.env.ENV_VARIABLE_NAME
on the client side:
const varName = "BASE_URL"; console.log(`${varName} = ${process.env[varName]}`); const { BASE_URL } = process.env; console.log(`${varName} = ${BASE_URL}`);
As explained above, you can declare environment variables in different files. These files are for environment variables that are usually made available in specific environments.
Next.js follows the order below when looking for an environment variable and stops after finding the variable it needs. The value of NODE_ENV
is set to development
in a development environment, production
in a production environment, and test
in a test environment:
process.env
env.${NODE_ENV}.local
env.local
(env.local
is not checked when NODE_ENV
is test
)env.${NODE_ENV}
.env
If you declare the same environment variable in multiple files, the environment variable declared in the lowest file in the above list wins.
In Next.js, you can create an environment variable by referencing or composing other environment variables using the ${VARIABLE_NAME}
syntax. Next.js will expand and replace any referenced variable with its actual value.
The example below uses the BASE_URL
and API_KEY
environment variables to create API_URL
. The value of the API_URL
variable will evaluate to https://www.logrocket.com/api/v1?apiKey=12345
:
BASE_URL="https://www.logrocket.com" API_KEY=12345 API_URL="${BASE_URL}/api/v1?apiKey=${API_KEY}"
Such composition avoids repetition and keeps your environment variable files organized. You can now reference each environment variable independently from your codebase:
console.log(process.env.BASE_URL); console.log(process.env.API_KEY); console.log(process.env.API_URL);
Cross-file environment variable referencing is also possible in Next.js. You can reference an environment variable declared in the env.local
file from the .env
file. However, you should pay attention to the order of the environment variable lookup as highlighted above if you have variables with similar names in different files.
Referencing a variable declared in .env.development
from .env.production
and vice versa won’t work because those environment variables will only be available in their respective environments.
Environment variables influence the way an application runs or behaves in different contexts and environments. Next.js, like most web frameworks, has the necessary setup for flexibly configuring and using environment variables in your application.
In this article, we explored the differences between private and public environment variables in Next.js. We also learned about functionalities that allow you to declare development-only and production-only environment variables, such as the .env.development
and env.production
files.
Finally, we learned that in a typical Next.js project, you only need the .env.local
file to store credentials that you want to keep secret. Always add the .env.local
file to your .gitignore
file to avoid exposing your secrets in a version control system like Git.
Happy coding!
Debugging Next applications can be difficult, especially when users experience issues that are difficult to reproduce. If you’re interested in monitoring and tracking state, automatically surfacing JavaScript errors, and tracking slow network requests and component load time, try LogRocket.
LogRocket is like a DVR for web and mobile apps, recording literally everything that happens on your Next.js app. Instead of guessing why problems happen, you can aggregate and report on what state your application was in when an issue occurred. LogRocket also monitors your app's performance, reporting with metrics like client CPU load, client memory usage, and more.
The LogRocket Redux middleware package adds an extra layer of visibility into your user sessions. LogRocket logs all actions and state from your Redux stores.
Modernize how you debug your Next.js apps — start monitoring for free.
Would you be interested in joining LogRocket's developer community?
Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.
Sign up nowLearn how to manage memory leaks in Rust, avoid unsafe behavior, and use tools like weak references to ensure efficient programs.
Bypass anti-bot measures in Node.js with curl-impersonate. Learn how it mimics browsers to overcome bot detection for web scraping.
Handle frontend data discrepancies with eventual consistency using WebSockets, Docker Compose, and practical code examples.
Efficient initializing is crucial to smooth-running websites. One way to optimize that process is through lazy initialization in Rust 1.80.