common .env file structures
most projects use multiple .env files for different environments.
- .env: Basic environment variables common to all environments
- .env.local: used only in the local development environment (excluding version control)
- .env.development: Used by the development environment
- .env.development.local: Local settings for the development environment (excludes versioning)
- .env.production: Used in production environments
- .env.production.local: Local settings for production environments (excludes versioning)
- .env.test: used in test environments
.local
files with suffixes store developer-specific settings and are typically excluded from version control.
general order of precedence
in general, environment variables are applied in the following order (This may vary depending on the framework or library)
- OS environment variables
- .env.[environment].local
- .env.[environment]
- .env.local
- .env
Loading priority of environment variables in Next.js
Next.js follows a clear order of precedence 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 value in Next.js
Values that can go into [MODE] in Next.js:
- production:
next start
ornext build
automatically when executed - development:
next dev
automatically on execution - test:
next test
automatically on runtime
forcing specific environment files
If you want to use variables from an environment other than production when building in Next.js, you can utilize the env-cmd
library.
# env-cmd 설치
npm install env-cmd --save-dev
// package.json
"scripts": {
"build:dev": "env-cmd -f .env.development.local next build"
}
# 실행
yarn build:dev
this method can be used in the following situations
- creating builds for a staging environment
- performing test builds with development environment settings
- testing locally with specific environment variables
cautions
common caveats
.local
files are removed from versioning by adding them to .gitignore- if the same variable name exists in multiple files, the value is determined by priority
- sensitive information must be stored in the
.local
file
Next.js-specific caveats
- environment variables that need to be exposed to the browser require the
NEXT_PUBLIC_
prefix - .env.test files are only loaded when running tests
- environment variables cannot be changed at runtime (determined at build time)
with this understanding of the prioritization of environment variable files, you can effectively manage the settings required for each environment based on the context of your project.