- Load environment variables from
.env*files - Expose variables to the browser using the
NEXT_PUBLIC_prefix
Loading environment variables
Create a.env file in the root of your project:
process.env automatically, making them available in Route Handlers and Server Components:
Next.js supports multiline variables in
.env* files:Variable expansion
Next.js automatically expands$VARIABLE references in .env* files:
process.env.TWITTER_URL resolves to https://x.com/nextjs. To use a literal $ in a value, escape it with \$.
Loading env outside of Next.js
To load environment variables outside the Next.js runtime (for example, in an ORM config or test runner setup), use the@next/env package:
Browser variables
By default, environment variables are only available server-side. To expose a variable to the browser, prefix it withNEXT_PUBLIC_:
Runtime environment variables
Server-side environment variables can be read at runtime during dynamic rendering. Useconnection() to opt into dynamic rendering:
Test environment variables
Next.js supports atest environment in addition to development and production. Use a .env.test file to define test-specific values:
.env.testis loaded whenNODE_ENV=test.env.localis not loaded in test environments (tests should produce the same results for everyone).env.testshould be committed to your repository;.env.test.localshould not
@next/env in your test setup:
Load order
Environment variables are resolved in the following order, stopping when a value is found:process.env.env.$(NODE_ENV).local.env.local(not checked whenNODE_ENVistest).env.$(NODE_ENV).env
NODE_ENV is development and a variable is defined in both .env.development.local and .env, the value in .env.development.local takes precedence.
Allowed values for
NODE_ENV are production, development, and test. If unassigned, Next.js automatically sets development for next dev or production for all other commands.Notes
.env.*files should remain in the root of your project, even if you use a/srcdirectory- Environment variable support was introduced in Next.js v9.4.0
