NEXT.JS ENV VARSWhat reaches the browserA Next.js app usually needs a mix of settings: a database URL, a payment provider's secret key, a webhook signing secret, and harmless values such as an analytics ID. They all sit in .env files and are all read through process.env, but only some of them may reach the browser. One prefix decides which, and a slip puts a secret inside JavaScript that any visitor can open. Here is how it works, and what we check before launch.
Which environment variables reach the browser?
Only the ones whose names start with NEXT_PUBLIC_. By default, Next.js makes environment variables available on the server only, so Server Components and route handlers can read a database password directly while the browser never receives it.
Two other paths also reach visitors:
- The
envoption innext.config.js. The docs mark it as legacy and say values set there are always included in the JavaScript bundle, whatever their name. - Props passed from a Server Component to a Client Component. They are serialised and sent to the browser, so a secret passed as a prop is as public as one with the prefix.
What does the NEXT_PUBLIC_ prefix actually do?
It copies the value into your JavaScript at build time. During next build, Next.js replaces each reference such as process.env.NEXT_PUBLIC_ANALYTICS_ID with the literal value from the build environment. Three things follow:
- The value is public. Anyone can read it in the files their browser downloads, so the prefix suits values designed to be public and nothing else.
- Changing it needs a rebuild. Once built, the app no longer responds to changes in these variables. Deploy one Docker image to several environments and every
NEXT_PUBLIC_value keeps its build-time value. - Only direct references are replaced. A lookup such as
process.env[name], or reading from a copy ofprocess.env, is not inlined.
How do you read a value at runtime instead?
Read it in server code that renders per request. The docs show a page that calls await connection() from next/server before reading process.env; using cookies, headers or another request-time API has the same effect. The variable is then evaluated at runtime, so one build can run in several environments with different values. When the browser genuinely needs a value that differs per environment, the docs suggest serving it from your own API rather than using the prefix.
Which .env files load first, and which belong in git?
Next.js looks in five places, in this order, and stops at the first match:
process.env, the real environment of the running process..env.$(NODE_ENV).local.env.local, skipped whenNODE_ENVistest..env.$(NODE_ENV).env
So a value set in your host's environment settings beats every file. If NODE_ENV is not set, Next.js uses development for next dev and production for other commands. Keep the files in the project root, even with a src folder, because Next.js does not load them from src.
The default create-next-app template adds all .env files to .gitignore, and the docs say you almost never want to commit them. Keep it that way: each developer has their own .env.local, and production secrets live in your host's settings or a secrets manager.
# .env.local (never committed)
DATABASE_URL="postgres://app:change-me@localhost:5432/app"
PAYMENT_SECRET_KEY="change-me"
WEBHOOK_SIGNING_SECRET="change-me"
NEXT_PUBLIC_ANALYTICS_ID="abcdefghijk"
# Wrong: this name would copy the secret into public JavaScript
# NEXT_PUBLIC_PAYMENT_SECRET_KEY="change-me"
// lib/payments.ts
import 'server-only' // a Client Component import now fails the build
export async function createCharge(amount: number) {
const key = process.env.PAYMENT_SECRET_KEY // right: read on the server
// call the payment API with key and amount
}
// app/checkout/page.tsx, a Server Component
<PayButton secretKey={process.env.PAYMENT_SECRET_KEY} /> // wrong: props reach the browserHow do you stop secret code reaching a Client Component?
Add import 'server-only' at the top of every module that reads a secret. Next.js calls the risk environment poisoning: modules can be shared by Server and Client Components, so a helper that sends process.env.API_KEY in a header can be imported into client code by mistake. With the import in place, that mistake becomes a build-time error instead of a quiet bug.
Better still, keep every secret read of process.env inside one data access layer, as the Next.js data security guide recommends. Treat Client Components as browser code, even though they also prerender on the server.
What should the team check before launch?
- Never prefix a database URL, an API secret key, a webhook signing secret or a private key. If a value lets someone act as your app, it stays on the server.
- Search the codebase for
NEXT_PUBLIC_and for anenvblock innext.config.js. Every value found must be safe on a public page. - Check the props of every Client Component for any value that came from a secret.
- Start each module that holds a secret with
import 'server-only'. - Keep
.env*files out of git, and catch secrets before they are committed: OWASP suggests detection in the editor or a pre-commit hook. - Rotate any secret that was ever exposed, whether in a commit, a public variable or a log. Deleting it from the code does not make it secret again; OWASP says to revoke and replace exposed keys immediately.
Where to start
List every variable in your .env files and where it is read. Any prefixed value that should not be public gets renamed, moved behind server code and rotated. Our web app development service builds Next.js apps with these checks in place. For a second opinion on an existing app, get in touch.
FAQ
Frequently asked questions
Why is my environment variable empty in a Client Component?
Because it has no NEXT_PUBLIC_ prefix. Next.js includes only prefixed variables in the client bundle and replaces unprefixed ones with an empty string, so a secret stays out of the browser. If the value is genuinely public, add the prefix and rebuild. If it is a secret, do the work in a Server Component, Server Action or route handler and send the browser only the result.
Which values are safe to give the NEXT_PUBLIC_ prefix?
Only values meant to be seen by anyone: an analytics ID, your site's public URL, or a key the provider says belongs in front-end code. Stripe, for example, says only its publishable keys are safe to expose outside your back end, and that you are responsible for protecting its other keys. A simple test: would you print the value on your home page?
Can one .env variable reference another?
Yes. Next.js expands $VARIABLE references inside .env files, so SITE_URL=https://example.com followed by LOGIN_URL=$SITE_URL/login gives process.env.LOGIN_URL the full address. If a real value contains a dollar sign, as some generated passwords do, the docs say to escape it as \$ so it is not read as a reference.
How do we load the same .env files in an ORM config or test runner?
Use the @next/env package, which Next.js uses internally to load .env* files. Call its loadEnvConfig function with the project directory, either in a small file your ORM config imports or in your test runner's global setup file. Tools that run outside Next.js then load variables the same way Next.js does.
Why are our .env.local values ignored when tests run?
Next.js skips .env.local when NODE_ENV is test, so every test run uses the same defaults for everyone. Put shared test values in .env.test, which the docs say belongs in the repository, so keep real secrets out of it. Personal overrides go in .env.test.local, which stays out of git. Test tools such as Jest usually set NODE_ENV for you.
Can React's taint APIs stop a secret reaching the browser?
They add a layer. Next.js supports React's experimental taint APIs through the experimental.taint option in next.config.js, which stops tainted objects or values from being passed to the client. The docs call it an additional layer of protection, not a replacement: you should still filter data in your data access layer before it reaches any component.
