documentation/blog/2024-12-10-next-env.md
This article was last updated on December 10, 2024, to add clear introduction and new section to Next.js ENV post..
In Next.js, environment variables come in very handy for storing API keys/URLs of sensitive nature in a proper and productive manner. They might be set up in files beginning with a dot {.env.} and would be autoloaded in the running Node.js process. You should expose these variables to your browser using the prefix: NEXTPUBLIC.
API_URL=https://api.example.com
NEXT_PUBLIC_ANALYTICS_ID=UA-123456
Access them in code:
const apiUrl = process.env.API_URL;
const analyticsId = process.env.NEXT_PUBLIC_ANALYTICS_ID
Type: .env.development, .env.production, or .env.test for different environments.
Order of Loading: Next.js checks .env.local first, then .env.
Best Practices: Keep secrets secure, do not commit .env files, and use cloud environment variable settings for production.
Next.js is a React framework that provides many out-of-the-box solutions for building single-page web applications. Under the hood, it handles a lot of tooling and configuration intuitively, making the process of developing applications a breeze.
One of the configurations Next.js handles by default are environment variables. Built-in support for environment variables got a lot easier in Next.js versions 9.4 and later. This means using environment variables in your applications has become seamless and straightforward.
An environment variable is a key-value pair (key=value) in which a value (or data) is assigned to a key (variable).
Environment variables are used in software development for many use cases; for providing configurations for different application running environments (e.g. development and production environments); for keeping sensitive application data out of application code from malicious users;
The following are valid examples of environment variables:
API_KEY='c4W39R56&gyh_ujij89$'
API_KEY=c4W39R56&gyh_ujij89$
ACCESS_TOKEN='A54EzZoU7o33SByHk1qr'
Basically, environment variables are added into Next.js apps through a env.local file. This will then load every variable into the Node.js process. Environment variables in Next.js are only available for use on the server. This means we can only use them in any of Next.js data fetching methods (getServerSideProps, getStaticProps, and getStaticPaths) or API routes.
For example, given a env.local file in your project root directory with the following content:
API_URL='https://dev.to/api/api/articles/{id}/unpublish'
API_KEY='your_secret_api_key_here'
Next.js will automatically load the variables as process.env.API_URL and process.env.API_KEY
which we can then use as shown below:
export async function getServerSideProps() {
const response = await axios({
method: "put",
url: process.env.API_URL,
header: {
Authorization: process.env.API_KEY,
},
data: {
id: 12,
},
});
}
NOTE: You should always put the env.local file in your project root directory to avoid Next.js running into errors.
We can also reference other variables in the same env.local file using a dollar ($) sign.
ADMIN_NAME='John'
ADMIN_ID=1234
PROTECTED_URL='https://api.example.com?admin=$ADMIN_NAME&id=$ADMIN_ID'
process.env.PROTECTED_URL will now evaluate to https://api.example.com?admin=John&id=1234.
Security is crucial when working with environment variables. Here are some best practices:
.env files before sharing. Use a tool like gpg for encryption: gpg --symmetric --cipher-algo AES256 .env
By following these practices, you can minimize the risk of leaks or misuse of sensitive data.
Improper use of environment variables can affect your app’s performance. Here’s how to optimize:
module.exports = {
env: {
API_URL: "https://api.example.com",
},
};
Optimizing variable handling improves your app’s performance and reduces overhead.
Environment variables may behave differently across platforms. Here’s how to maintain consistency:
Example for Vercel: 1. Go to your project settings. 2. Add variables under “Environment Variables.” 3. Deploy your app.
services:
app:
build: .
environment:
- API_URL=https://api.example.com
By addressing platform-specific differences, you can ensure seamless cross-environment compatibility for your app.
Like we mentioned earlier, Next.js env is only available for use on the server by default. However, Next.js provides us a solution to expose the variables to the browser. By adding a NEXT_PUBLIC_ prefix to a variable defined in env.local Next.js will automatically make it accessible for use in the browser and anywhere else in our application.
For example:
# env.local
NEXT_PUBLIC_GOOGLE_ANALYTICS_ID='your_google_analytics_id_here'
Now we can use it in our code like so:
...
return (
<>
<Script strategy="lazyOnload" src={`https://www.googletagmanager.com/gtag/js?id=${process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS_ID}`} />
<Script strategy="lazyOnload">
{`
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS_ID}', {
page_path: window.location.pathname,
});
`}
</Script>
...
</>
)
Here's what is going on above.
In env.local we defined a NEXT_PUBLIC_GOOGLE_ANALYTICS_ID variable which holds the value for our Google analytics ID. The prefix NEXT_PUBLIC_ lets us use the variable process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS_ID in client side code (/pages/_app.js). Note that _app.js runs on both the client and server.
We added two <Script/> components from Next.js to add Javascript code to configure google analytics. The <Script/> component optimizes external scripts that are loaded in a Next.js application by using strategies to improve browser and user experience.
In the previous code, we added lazyOnload strategy to both scripts; this is to tell the browser we want the analytics to be generated when all other resources have been fetched and the browser is idle.
A single .env.local file is usually all you need for your environment variables but at times you may want to specify different configurations for different application environments. Next.js allows us to take charge of how we want to configure the variables. There are basically three application environments we'll talk about in this article. These are:
next dev)next start)A .env file can be used to specify a default configuration for all three application environments. Note that if the same variables are declared in a .env.local, it'll override the defaults. .env and .env.local files must be added to .gitignore since they are where sensitive application data are stored.
You can specify development environment variables in a .env.development file. This file should be kept in your project directory.
Use a .env.production file for environment variables that are particular to production. This file should also be kept in your project directory.
For example, to add environment variables to your live deployments (if you use Vercel to deploy your application), you can add environment variables to a project by going to Settings on your dashboard and clicking on Environment Variables. The UI should look like below:
Next.js will always search for an environment variable in five places in your application code in the following order until it's found:
process.env (start).env.$(NODE_ENV).local (where NODE_ENV can be any of development, production or test).env.local.env.$(NODE_ENV) (where NODE_ENV can be any of development, production or test).env (end)So for example if you define a variable in .env.development.local and then redefine it in env.development, the value in env.development.local will be used.
We can also use a .env.test to specify environment variables for testing purposes. In order to use default test environment variables, you must set NODE_ENV to test. Here's an example showing how you can do this in package.json:
...
"scripts": {
"dev": "next dev",
"start": "next start",
"test": "NODE_ENV=test mocha spec"
}
...
Other tools like jest will configure the settings for you by automatically setting the environment to test.
Note that Next.js will configure your environment variables differently when you're in a test environment. Variables from .env.local, .env.production or .env.development won't be loaded in order for test executions to use the same default configuration. You must include the .env.test file in your project directory to prevent it from being overridden by .env.local.
In this article we learned about what environment variables are and how to use them in Next.js. We also implement how to define Next.js env's for different application running environments.