In the table below you'll see how environment variables can be exposed to the browser with Next.js.
In general only .env.local
or .env
are needed for this, but the table also features the usage of .env.development
and .env.production
.
Variable Name | Value | Added By |
---|---|---|
NEXT_PUBLIC_ENV_VARIABLE | public_variable | .env |
NEXT_PUBLIC_ENV_LOCAL_VARIABLE | .env.local | |
NEXT_PUBLIC_DEVELOPMENT_ENV_VARIABLE | .env.development | |
NEXT_PUBLIC_PRODUCTION_ENV_VARIABLE | public_production_variable | .env.production |
.env.local
is not added by the example, because it must be ignored by git, but you can add it manually:
cp .env.local.example .env.local
Variables in .env.production
won't be available if the app is running in development:
npm run dev
Similarly, variables in .env.development
won't be available if the app is running on production:
npm run build && npm run start
Once you run the app, you'll see logs like these in the terminal:
info - Loaded env from /home/user/../.env.local
info - Loaded env from /home/user/../.env.development
info - Loaded env from /home/user/../.env
The order is important, the first loaded env will have a higher priority.
.env
will not overwrite any variables defined in .env.local
or .env.development
.