Common .env File Structure
Most projects use multiple .env files tailored to different environments.
- .env: Basic environment variables commonly used in all environments
- .env.local: Used only in the local development environment (excluded from version control)
- .env.development: Used in the development environment
- .env.development.local: Local settings for the development environment (excluded from version control)
- .env.production: Used in the production environment
- .env.production.local: Local settings for the production environment (excluded from version control)
- .env.test: Used in the test environment
Files with the
.local
suffix store individual developer settings and are typically excluded from version control.
General Priority Order
Generally, environment variables are applied in the following order (may vary depending on the framework or library):
- OS environment variables
- .env.[environment].local
- .env.[environment]
- .env.local
- .env
Environment Variable Loading Priority in Next.js
Next.js follows a clear priority when loading environment variables:
- .env.local: Highest priority
- .env.[MODE].local: Local settings for a specific environment
- .env.[MODE]: Specific environment settings
- .env: Default settings
MODE Values in Next.js
Values that can be used for [MODE] in Next.js:
- production: Automatically specified when running
next start
ornext build
- development: Automatically specified when running
next dev
- test: Automatically specified when running
next test
Forcing Specific Environment Files
If you want to use variables from an environment other than production when building in Next.js, you can use the env-cmd
library.
# Install env-cmd
npm install env-cmd --save-dev
// package.json
"scripts": {
"build:dev": "env-cmd -f .env.development.local next build"
}
# Execution
yarn build:dev
This method can be used in the following situations:
- Creating builds for staging environments
- Performing test builds with development environment settings
- Local testing with specific environment variables
Precautions
Common Precautions
- Add
.local
files to .gitignore to exclude them from version control - When the same variable name exists in multiple files, the value is determined according to priority
- Sensitive information must be stored in
.local
files
Next.js Specific Precautions
- Environment variables that need to be exposed to the browser require the
NEXT_PUBLIC_
prefix - The .env.test file is only loaded during test execution
- Environment variables cannot be changed at runtime (determined at build time)
Let's effectively manage the settings needed for each environment according to your project situation while understanding the priority of environment variable files.