A Next.js environment variable is undefined in the browser or after deploy
process.env.API_URL is undefinedShort answer
Next.js only gives the browser variables whose names start with NEXT_PUBLIC_, and it copies their values into the JavaScript at build time. A variable without the prefix, read through a dynamic lookup, set after the build, or stored in a .env file that Next.js never loads will be undefined. Find which of the four applies, then rebuild.
Fix it fast
1Find out which cause you have
Say where the code runs. A Server Component, route handler or proxy reads the real environment. Code that ships to the browser only sees values that were copied in during next build. Search the build output for the value to see whether the copy happened.
grep -rn "process.env" app src components lib 2>/dev/null | head -30 # after a build: is the value inside the browser bundle? npx next build && grep -rl "the-value-you-expect" .next/static | head2Match what you see, then jump to its fix
- 1
The value is set on the server and printed in the terminal, yet it is undefined inside a Client Component or an event handler.The name has no NEXT_PUBLIC_ prefix but the code runs in the browserFix - 2
process.env.NEXT_PUBLIC_X works when typed out, but the same name is undefined when built from a string or taken from a copy of process.env.The variable is read through a dynamic lookupFix - 3
Works with next dev. After next build or in a Docker image, the NEXT_PUBLIC_ value is old, empty or the same in every environment.The value was set after the build, or the build ran with other valuesFix - 4
The variable is missing everywhere, including the server, or a value in .env.local is ignored in tests.Next.js does not load the .env file you editedFix
- 1
What does the error look like?
process.env.API_URL is undefinedTypeError: Cannot read properties of undefinedThe variable prints in the terminal but is empty in the browserThe value works with next dev but is wrong after next build
Cause 1 of 4
The name has no NEXT_PUBLIC_ prefix but the code runs in the browser
1Check
Variables without the prefix stay in the Node.js environment. Find the file that reads the variable and check whether it has 'use client' or is imported by one.
grep -rln "use client" app src components 2>/dev/null
grep -rn "process.env.API_URL" app src components lib 2>/dev/null2Fix
For a value that is safe to show to anyone, rename it with the NEXT_PUBLIC_ prefix and update every reader. For a secret, keep the name as it is and read it on the server only, then pass the result to the browser.
# .env
NEXT_PUBLIC_API_URL=https://api.example.com
// Client Component
const base = process.env.NEXT_PUBLIC_API_URL3Verify
Restart the dev server (or rebuild) and print the value in the browser console.
npm run devConfirmed by nextjs.org
Cause 2 of 4
The variable is read through a dynamic lookup
1Check
Next.js replaces the exact expression process.env.NEXT_PUBLIC_NAME. A lookup with a variable key, or a copy such as const env = process.env, is not replaced.
grep -rnE "process\.env\[|= process\.env\b|\{[^}]*\} = process\.env" app src components lib 2>/dev/null2Fix
Write the full name on every read.
// does not work in the browser
const key = 'NEXT_PUBLIC_ANALYTICS_ID'
const id = process.env[key]
// works
const id = process.env.NEXT_PUBLIC_ANALYTICS_ID3Verify
Rebuild and search the browser bundle for the value.
npx next build && grep -rl "the-value-you-expect" .next/static | headConfirmed by nextjs.org
Cause 3 of 4
The value was set after the build, or the build ran with other values
1Check
NEXT_PUBLIC_ values are frozen into the JavaScript when next build runs. Changing the variable on the running server, or building one image and promoting it between environments, does not change them.
env | grep NEXT_PUBLIC_
docker build --help | grep -i build-arg2Fix
Set the variable in the environment of the build step and rebuild. If one build must serve several environments, read the value on the server at request time instead, after a request-time API such as connection() has opted the page into dynamic rendering, or hand it to the client through your own API.
// app/page.tsx (Server Component, read at request time)
import { connection } from 'next/server'
export default async function Page() {
await connection()
const apiUrl = process.env.API_URL
return <p>{apiUrl}</p>
}3Verify
Change the variable, restart the server and reload the page. The new value shows without a rebuild.
API_URL=https://staging.example.com npm run startConfirmed by nextjs.org
Cause 4 of 4
Next.js does not load the .env file you edited
1Check
Next.js loads .env files from the project root, not from src. It looks in process.env first, then .env.$(NODE_ENV).local, .env.local, .env.$(NODE_ENV) and .env. When NODE_ENV is test, .env.local is skipped.
ls -a . src | grep -E "^\.env"
echo "NODE_ENV=$NODE_ENV"2Fix
Move the file to the project root, put test values in .env.test, and restart. If a tool outside Next.js needs the same files, load them with @next/env.
mv src/.env.local ./.env.local
// jest or script setup
import { loadEnvConfig } from '@next/env'
loadEnvConfig(process.cwd())3Verify
Restart next dev and print the variable from a Server Component or route handler. It now has a value.
npm run devConfirmed by nextjs.org
How do I stop it coming back?
- Name every browser-visible variable with NEXT_PUBLIC_ and keep secrets without it.
- Always write process.env.NEXT_PUBLIC_NAME in full, never through a variable or a copy.
- Pass NEXT_PUBLIC_ values as build arguments in CI and in Docker builds, and rebuild when they change.
- Keep .env files in the project root and out of git, except shared defaults.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
Related fixes
Web apps
Next.js shows Application error: a client-side exception has occurred
An error in production with a digest and no readable message
This white page is Next.js's fallback when an uncaught error unmounts the React tree, and it hides the real message.
4 causes, each with a fixWeb apps
Apollo Server rejects a request as a potential CSRF
HTTP 400 Bad Request from the GraphQL endpoint
Apollo Server's CSRF prevention is on by default.
3 causes, each with a fixWeb apps
Clerk cannot read its publishable key in a Next.js app
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY is undefined
Clerk reads NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY.
3 causes, each with a fixWeb apps
The shell cannot find create-next-app
command not found: create-next-app
create-next-app is not meant to be installed as a shell command.
2 causes, each with a fixWeb apps
ESLint fails with: Cannot find module 'next/babel'
ESLint stops on the first file with a Babel or parser error instead of listing lint results
next/babel is a Babel preset that ships inside the next package.
3 causes, each with a fixWeb apps
Firebase Auth says the API key is not valid
Firebase: Error (auth/api-key-not-valid.-please-pass-a-valid-api-key.)
The apiKey your app sends is either empty, wrong, or blocked.
4 causes, each with a fix