Next.js Environment Variables Not Working? Why process.env Is Undefined
An environment variable that works in one place and is undefined in another is almost always being read where it does not exist: in the browser, at build time, from the wrong file or on a server that never received it. This guide matches each symptom to its cause, and the Next.js behavior was reproduced on version 16.3.5.
Ali RehmanFreelance Web Developer
On this page 16 sections
You add a value to .env.local, and in one file it works. In another, process.env gives you undefined. Or it worked yesterday, and after the deploy the site shows an old value, or only half of it.
NEXT_PUBLIC_, only where the full name is written out, and only with the value from the build. Server code gets every variable, but a page that was rendered during the build keeps the values it had then. The table below matches each symptom to its cause.Every Next.js behavior described here was reproduced on 14 November 2026 in a small test project running Next.js 16.3.5: 46 checks across three builds, the default Turbopack build, a webpack build and a standalone build. The method and its limits are at the end. Where the result differs from the documentation, the article says so.
First, find where the value is read
The same line, process.env.API_URL, can run in four places in a Next.js app, and each place gets its values at a different moment.
- On the server, during the build. Pages that can be rendered ahead of time are rendered by
next build, and they keep the values the build saw. - On the server, for each request. Dynamic pages, route handlers and
proxy.jsreadprocess.envwhen the request arrives. - In the browser. Client components only get what the build wrote into the JavaScript: names that start with
NEXT_PUBLIC_, and anything in theenvoption ofnext.config.js. - Outside Next.js. Test runners, scripts and configuration files for other tools do not load
.envfiles by themselves.
Client components also run once on the server to produce the first HTML. That is why a value can appear for a moment and then disappear, which is section 3.
What you see
→ section: most likely cause
undefined in the browser only
→ 1: no NEXT_PUBLIC_ prefix
Prefix set, still undefined in browser
→ 2: name built at runtime
Flashes, then undefined; hydration error
→ 3: server variable in client code
Old value after a change
→ 4: frozen at build time
undefined on the server too
→ 5: wrong folder, file or mode
Value cut off at a $
→ 6: $ starts a variable reference
Works locally, not on Vercel
→ 7: wrong environment or no redeploy
Works with next start, not in Docker
→ 8: .env.local was not copied
undefined in tests or scripts
→ 9: nothing loaded the .env files
Tested on Next.js 16.3.5.
Vercel row: from Vercel’s docs.1. Undefined in the browser: the name needs NEXT_PUBLIC_
By default a variable exists only on the server. For browser code to read it, its name must start with NEXT_PUBLIC_. During the build, Next.js finds each process.env.NEXT_PUBLIC_… in the code and replaces it with the value itself, as plain text.
In the test, a client component read a variable without the prefix. On the server it had a value; in the browser it was undefined, with both Turbopack and webpack. One page of the documentation says such names are replaced with an empty string, so a check for an empty string would miss this. A search of the compiled browser files found the prefixed value in one file and the unprefixed value in none.
The fix is to add the prefix, but only to values that anyone may read. A prefixed value is plain text in the JavaScript that every visitor downloads. An analytics ID or the address of a public API is fine. A database password, a private API key or a signing secret is not. Keep those without the prefix and read them on the server, as section 3 shows.
There is one more way to send a value to the browser: the env option in next.config.js. Its documentation says values set there are always included in the JavaScript, prefix or not, and the test confirmed it. Never put a secret there.
2. The prefix is there, but the full name is not written out
The build replaces text, so it only recognises a name written in full, as process.env.NEXT_PUBLIC_NAME. If the name is assembled at runtime, or read from a copy of process.env, there is nothing to replace, and the browser has no process.env object holding your values.
// Works: every name is written out in full
export const publicEnv = {
apiUrl: process.env.NEXT_PUBLIC_API_URL,
siteName: process.env.NEXT_PUBLIC_SITE_NAME,
};
// undefined in the browser: destructuring
const { NEXT_PUBLIC_API_URL } = process.env;
// undefined in the browser: name passed in
function readEnv(name: string) {
return process.env[name];
}
readEnv("NEXT_PUBLIC_API_URL");Both failing patterns returned undefined in the browser with both bundlers. The helper catches people because it looks like good practice: one function that reads and checks every variable. It works on the server and fails in the browser. If you want that check, start from an object like publicEnv above, where the build can see every full name.
Two more patterns gave mixed results. A constant key, const key = "NEXT_PUBLIC_API_URL" followed by process.env[key], worked with Turbopack, the default bundler in version 16, and was undefined with webpack. A direct alias, const env = process.env followed by env.NEXT_PUBLIC_API_URL, worked with both. The environment variables guide lists both as lookups that are not inlined. Follow the guide: what worked in one version is an implementation detail, and the full name works everywhere.
3. A server variable in a client component
This one looks like a flicker. The page shows the value for a moment, then it changes to “undefined” or disappears, and the console shows an error. A client component runs on the server first to build the HTML, and there the variable exists. In the browser it does not, and React notices that the two results differ.
In development the test page logged “Hydration failed because the server rendered text didn't match the client.” The production build logged only “Minified React error #418”, which is the same error in short form. After hydration, the page showed “undefined”.

The serious part was in the HTML. The test page was static, so it was rendered during the build, and the secret value from the build was written into the page. Anyone could read it with View Source, while the screen showed “undefined”. Starting the server with a different value did not change that HTML.
The fix is to read the value in a server component or a route handler and give the client component only the result it needs, never the secret. To make the mistake impossible, keep the code that reads secrets in a file that starts with import "server-only". Importing that file into a client component is then a build-time error. The data security guide goes a step further and recommends that only one data access layer reads process.env.
// lib/billing.ts
import "server-only";
export async function getPlanName() {
const key = process.env.BILLING_SECRET_KEY;
// ...call the billing API with the key...
return "Pro";
}
// app/account/page.tsx (a server component)
const plan = await getPlanName();
// Pass the result, not the key:
return <PlanBadge name={plan} />;4. The value is old: it was fixed at build time
If a value is right in one place and old in another, compare when each place read it. The test built the app with one set of values and then started it with another:
- A static page showed the build values for every variable, server-only ones included.
- A page that called
await connection()fromnext/servershowed the new server values on every request. - On that same dynamic page, the
NEXT_PUBLIC_value was still the build value. Next.js replaces those names in server code too, so the running server cannot change them. - A route handler and
proxy.jsalso read the new server values, and also kept the build value for the public one.
So there are two different fixes. For a server value on a static page, make the page dynamic: connection() is the documented way, and reading cookies or headers has the same effect. Do it only for pages that need it, because a dynamic page is rendered for every visitor instead of once. For a NEXT_PUBLIC_ value there is no runtime fix: build the app again with the new value.
The build output shows which pages are frozen. In its route list, ○ marks a static page and ƒ a dynamic one. In the test, a page that read process.env and nothing else was marked ○: reading a variable does not make a page dynamic.
If one build has to run in several places with different public values, for example a Docker image promoted from staging to production, the guide’s advice is to serve those values from your own endpoint. Another option is to read them in a server component on a dynamic page and pass them down as props.
5. Undefined everywhere: file name, folder or mode
When the value is missing on the server as well, the file was not loaded. Check three things.
- 1The folder. The
.envfiles belong in the project root, next topackage.json. With asrcfolder, files inside it are ignored: in the test, a variable defined only insrc/.env.localwas undefined everywhere. - 2The name. Next.js reads
.env,.env.local,.env.development,.env.production,.env.testand the.localversion of each mode. A file called.env.devorenv.localis not read, and Windows Notepad can save.env.localas.env.local.txtwhile hiding the extension. - 3The mode.
next devruns in development mode;next buildandnext startrun in production mode, and each mode reads its own files. In the test,.env.developmentwas ignored by the production build and server, and.env.productionand.env.production.localwere ignored bynext dev. LeaveNODE_ENVunset unless you have a reason: Next.js sets it from the command.
When a name is defined in several places, the first one found wins. The test confirmed this order for production mode:
- 1A real environment variable: set in the shell, by the host or in the container.
- 2
.env.production.local - 3
.env.local - 4
.env.production - 5
.env
In development mode, read “development” for “production”. With NODE_ENV=test, .env.local is skipped, which is section 9. The first line matters more than people expect. A variable that already exists on the machine beats every file, so an old value set there silently overrides the one you keep editing. In the test, a value set in the shell replaced the one in .env.local.
6. The value is cut off at a dollar sign
A password written as pa$word123 came back as pa in the test. In a .env file, Next.js treats $ as the start of a reference to another variable, so $word123 was read as a variable that does not exist and replaced with nothing. The feature is deliberate and useful: ITEMS_URL=$BASE_URL/items was expanded correctly.
Quotes do not protect the value. Single and double quotes both gave pa, unlike a Unix shell, where single quotes stop expansion. What works is a backslash before the dollar sign, as the guide says:
# Three separate examples
DB_PASSWORD=pa$word123 → pa
DB_PASSWORD='pa$word123' → pa
DB_PASSWORD=pa\$word123 → pa$word123Generated passwords and tokens often contain a $, so this failure tends to appear right after a credential is changed. If a database or email login suddenly fails with what looks like the right password, log the length of the value on the server, not the value, and compare it with the real one.
7. Vercel: the right environment, then a new deployment
On Vercel, variables are set in the project settings, and each one is assigned to one or more environments: Production, Preview and Development. Vercel’s documentation has a troubleshooting table, and its first row is the most common surprise: a change in the dashboard does nothing to the running site, because changes apply only to new deployments. Redeploy after every change.
- Check which environments the variable is assigned to. A variable added only to Production is missing in preview deployments, and the other way round.
- A
NEXT_PUBLIC_value is written into the build, so it has to exist when Vercel builds the app, not only later. - The same table lists lookups such as
process.env[name]as a cause of undefined browser values, which is section 2. - In a Turborepo project, variables are left out of the build cache key unless
turbo.jsonlists them, so a cached build made with other values can be reused. - For local work,
vercel env pullwrites the Development variables into.env.local. Run it again after changing them in the dashboard.
This part was not tested on Vercel; it comes from Vercel’s documentation, checked on 14 November 2026. The Next.js rules behind it apply on any host that builds the app for you: public values must exist when the build runs, and a change needs a new build.
8. Docker and standalone: .env.local stays behind
With output: "standalone", which most Docker setups use, the build creates a small server in .next/standalone. In the test, the build copied two files next to server.js: .env and .env.production. It did not copy .env.local or .env.production.local.

When server.js was started with no variables set, it read those two files and nothing else. Values that existed only in .env.local were undefined. So was a server variable that had been set in the shell during the build: a build-time value does not reach the server unless the build wrote it into the code. Only the NEXT_PUBLIC_ value, already in the JavaScript, still had its build value.
That gives three rules for a container:
- 1Give server values to the container when it starts, for example with
docker run -eor the platform’s settings. A real environment variable beats the files, so one image can run in staging and in production; the self-hosting guide describes this use. - 2Give
NEXT_PUBLIC_values to the build, for example as build arguments, because that is when they are written into the JavaScript. Changing them on a running container has no effect. - 3Do not rely on
.env.localinside an image, and keep secrets out of.envand.env.productionif those files are part of the build: the test showed both being copied into the standalone folder.
The standalone server also reads PORT and HOSTNAME, as the output documentation explains. Docker itself was not part of the test: the standalone server was started directly with Node.js.
9. Tests, scripts and config files outside Next.js
Next.js loads .env files for its own commands. A test runner, a seed script or a configuration file for another tool runs in plain Node.js and sees only real environment variables. The documented fix is loadEnvConfig from @next/env, the same loader Next.js uses:
// envConfig.ts: import this file first
import { loadEnvConfig } from "@next/env";
loadEnvConfig(process.cwd());One difference catches people in tests. When NODE_ENV is test, which test runners usually set, .env.local is skipped on purpose so that every run uses the same values. In the test, loadEnvConfig with NODE_ENV=test loaded only .env.test and .env; without it, the same call also loaded .env.local. Put values for tests in .env.test.
Do you need to restart after editing .env?
A common tip is to restart next dev after every change. In version 16.3.5 the answer depends on what reads the value:
next dev: no restart for the four files it watches in the project root:.env,.env.local,.env.developmentand.env.development.local. In the test, saving.env.localprinted “Reload env: .env.local” in the terminal, and the next page load showed the new value on the server and in the browser. If that line does not appear, you edited a different file.next startorserver.js: restart for server values, because the files are read when the server starts. Build again forNEXT_PUBLIC_values and static pages.- Vercel and other hosted builds: redeploy, as in section 7.
- Tests and scripts: run them again; they load the files once, when they start.
The list of watched files comes from the development server’s source, and the message from the server that reloads them. Changes to next.config.js are a separate case and were not part of the test.
Fixes that create new problems
- Adding
NEXT_PUBLIC_to a secret to make the error go away. It goes away because the secret is now in the JavaScript every visitor downloads. If that was ever deployed, change the secret itself, not only the code. - Moving a secret into the
envoption ofnext.config.js. The same leak by another route: values there always reach the browser. - Making every page dynamic. It fixes stale server values, but then every page is rendered for every visitor. Make only the pages that need runtime values dynamic.
- Committing
.env.localto get values onto the server. A secret in Git history stays there. Use the host’s settings. - Wrapping a value in quotes to protect a
$. In Next.js it does not help; write\$instead. - Printing all of
process.envto debug. Logs are kept and shared. Print whether a value exists, or its length.
Secrets that sign logins or tokens are the most urgent to change after a leak; the authentication guide explains what they protect. For the wider picture, see website security for small businesses.
Verify the fix the way production runs
- 1Build and start the production version locally with the variables the host will have:
next build, thennext start. Development mode reads other files and behaves differently. - 2Read the route list in the build output. A page that must show runtime values has to be marked
ƒ, not○. - 3Search the compiled browser files for a distinctive part of each secret. In the test, the server-only value was in none of the files under
.next/static; anything you find there is public. - 4Open View Source on pages with client components and search again. A hydration leak shows up in the HTML, not in the JavaScript.
- 5Make the server fail loudly when a required variable is missing. The
registerfunction ininstrumentation.tsruns once when the server starts, which is the right moment to check. - 6After deploying, test in a private window, and write down the change that fixed it.
# After next build, from the project folder.
# Search for part of the value only.
# No output: not in the browser files.
grep -rl "part-of-the-value" .next/staticWhen to hand it to a developer
Get help when one build must run in several environments with different public values, when a secret may already have been exposed and needs to be changed everywhere it is used, when a monorepo or a build cache is involved, or when servers behind a load balancer disagree about a value. Those cases need someone who reads the build, the hosting settings and the code together.
Send the variable names but never their values, where each one is set, the Next.js version, where the site is hosted, how it is built and deployed, and which symptom from the table you see. Debugging like this is part of my Next.js development service, and you can send the details here. If you are hiring someone else, the guide on how to hire a Next.js developer lists what to ask. For pictures that break only in production, see the guide to next/image errors.
Frequently asked questions
Why is process.env undefined in my Next.js client component?
The browser only gets variables whose names start with NEXT_PUBLIC_, and only where the full name is written as process.env.NEXT_PUBLIC_NAME. Destructuring process.env or reading it through a helper function gives undefined in the browser. If the value is a secret, do not add the prefix; read it in a server component instead.
Do I need to restart Next.js after changing .env.local?
Not with next dev in version 16.3.5: the development server reloads .env, .env.local, .env.development and .env.development.local and prints “Reload env”. A production server needs a restart for server values, and a new build for NEXT_PUBLIC_ values and static pages.
Why do environment variables work locally but not on Vercel?
Usually the variable is not assigned to the environment being deployed, such as Preview, or it was added after the last deployment. Changes apply only to new deployments, and NEXT_PUBLIC_ values must exist when Vercel builds the app.
Where should the .env file go in Next.js?
In the project root, next to package.json, even when the code lives in a src folder. Next.js ignores .env files inside src.
How do I use runtime environment variables in Docker?
Read server values in code that runs per request, such as a page that calls connection(), a route handler or proxy.js, and pass them with docker run -e. NEXT_PUBLIC_ values are fixed in the JavaScript at build time, so set them when the image is built, or serve them from your own endpoint if one image must run with different public values.
Is it safe to put API keys in NEXT_PUBLIC_ variables?
Only keys that are meant to be public, such as an analytics ID or a key the provider describes as safe to use in the browser. The value is plain text in the JavaScript every visitor downloads. Secret keys must keep a name without the prefix and be read on the server.
Sources, test and review scope
The rules come from the Next.js environment variables guide, the references for the env option, output and connection(), the server and client components, self-hosting, data security and instrumentation guides, and Vercel’s environment variables documentation. All are linked above and were checked on 14 November 2026. The development reload was read from the Next.js 16.3.5 source, also linked above.
The behavior was reproduced in a new App Router project with a src folder, five routes and a proxy.js, built with Next.js 16.3.5, React 19.2.4 and Turbopack on Node.js 24, then built again with webpack and as a standalone server. Values were read from the rendered HTML, from JSON responses, from the browser after hydration and from the compiled browser files. Across 19 recorded steps, all 46 expectations matched, including these:
- 1Production order: a real variable, then
.env.production.local,.env.local,.env.productionand.env;next devused the development files instead. - 2A static page kept every build value; a page with
connection(), a route handler andproxy.jsread new server values; the public value kept its build value everywhere. - 3Destructuring and a helper function were undefined in the browser with both bundlers; a constant key worked only with Turbopack; a direct alias worked with both.
- 4A server-only variable in a client component caused a hydration error and was written into the prerendered HTML.
- 5
pa$word123becamepawith and without quotes, and stayed whole when written aspa\$word123. - 6Editing
.env.localduringnext devprinted “Reload env: .env.local” and served the new values without a restart. - 7The standalone build copied
.envand.env.productionbut not the.localfiles, andserver.jsread the copied files when it started. - 8
loadEnvConfigskipped.env.localwithNODE_ENV=test.
Limits: one Windows machine with the Node.js server. The test did not cover Vercel or any other host’s settings, Docker images, the Edge runtime, the Pages Router or Jest and Vitest themselves; the test-mode check called @next/env directly. The variable names and values were made up for the test. Prepared with AI-assisted research and testing; I reviewed the results against the linked sources before publishing.
Written by
Ali Rehman - Freelance Web Developer
I work on WordPress websites, practical fixes and scoped web applications. Read my background and skill scope, or send a project brief to discuss a written plan and quote - start here.
More articles by Ali Rehman →