In Next.js, managing configurations for different environments (development, testing, production) can be achieved by utilizing different .env files. Next.js automatically loads environment variables and follows specific rules for loading .env files tailored to distinct environments. Here are the steps to implement this:
-
Create
.envfiles: In the root directory of your Next.js project, create the following.envfiles to define environment variables:.env.local: This file overrides variables in other.envfiles and is not tracked by Git version control, typically used for sensitive information..env.development: Loaded exclusively when runningnext dev(i.e., in development mode)..env.production: Loaded exclusively when runningnext start(i.e., in production mode)..env.test: Used during automated testing; manual configuration of the loading mechanism is required..env: The default environment variables file, loaded in all environments but overridden by specific environment files.
-
Set environment variables: In each
.envfile, define necessary environment variables in the following format:plaintext# .env.local API_SECRET=local_secret # .env.development API_URL=https://dev.example.com/api # .env.production API_URL=https://prod.example.com/api -
Load environment variables: Next.js automatically handles loading these variables without additional configuration. Access them in your code using
process.env:javascriptconsole.log(process.env.API_URL); // Output reflects the value from the corresponding .env file based on the current environment -
Use environment variables: Directly leverage
process.envin Next.js pages, API routes,getServerSideProps, orgetStaticPropsfor server-side code. -
Expose environment variables to the browser: To use environment variables in the browser, prefix the variable name with
NEXT_PUBLIC_:plaintextNEXT_PUBLIC_ANALYTICS_ID=xyz123This enables safe usage in client-side JavaScript:
javascriptconsole.log(process.env.NEXT_PUBLIC_ANALYTICS_ID); // Accessible on the client side
Example:
Suppose you have an API URL that differs between development and production environments. Configure it as follows:
-
In
.env.developmentfile:plaintextAPI_URL=https://dev.api.example.com -
In
.env.productionfile:plaintextAPI_URL=https://api.example.com
When running next dev in development mode, process.env.API_URL will be https://dev.api.example.com. When running next start in production mode, the environment variable will be https://api.example.com.
By implementing this approach, you can load environment variables based on the current runtime environment without modifying your code, which enhances project configuration management and code maintainability.