Typical Runtime Error (Next.js / React .env Failure)
When syntax errors, unquoted special characters, missing keys, or public-prefix secret leaks slip into a Next.js / React .env file, your runtime or audit pipeline surfaces an error like the output below:
Security Audit Alert: Sensitive key NEXT_PUBLIC_SUPABASE_SERVICE_ROLE_KEY was inlined into .next/static/chunks/app/layout-*.js and is publicly readable in browser DevTools.
How Next.js / React Loads .env Files, Precedence & Security Boundaries
Next.js App Router cleanly separates server-only environment variables from browser-exposed variables using a single naming rule: any variable prefixed with NEXT_PUBLIC_ is statically replaced by Webpack/Turbopack into your client JavaScript bundle at build time. Accidentally adding NEXT_PUBLIC_ to a Stripe secret key, Supabase service_role key, AWS access key, or database password exposes full administrative credentials inside public /_next/static/chunks/*.js files to every visitor on the internet.
Developers frequently make this mistake when an unprefixed variable like process.env.STRIPE_SECRET_KEY returns undefined inside a "use client" component, and they blindly prepend NEXT_PUBLIC_ to silence the error instead of moving the API call into a Server Component, Server Action, or Route Handler. Automated static linting before committing or deploying prevents catastrophic credential leaks.
Next.js also enforces a strict multi-file precedence cascade (.env.production.local > .env.local > .env.production > .env) and evaluates NEXT_PUBLIC_* variables at next build time rather than container startup time. If you build one Docker image in CI and inject a different NEXT_PUBLIC_API_URL at runtime via docker-compose.yml, Client Components still call the old build-time URL baked into the JS bundle.
Running your .env.local and .env.production files through this zero-upload browser checker immediately catches NEXT_PUBLIC_ secret leaks, unquoted # characters in NEXTAUTH_SECRET, leftover localhost values in NEXTAUTH_URL, and drift against .env.example.
For teams deploying Next.js to Vercel, Cloudflare, or Docker VPS hosts, pairing build-time Zod schema validation (such as @t3-oss/env-nextjs) with strict server-only module guards (import "server-only") ensures a missing or leaked environment variable fails CI immediately instead of crashing production.
In production Next.js monorepos and multi-environment Vercel or Docker pipelines, auditing .env.local and .env.production before every release protects against both silent runtime crashes and accidental client-bundle leaks. Keep a strict boundary between Server Component secrets (never prefixed) and browser-safe configuration (NEXT_PUBLIC_*), document every required key inside .env.example, and rotate any credential immediately if it was ever compiled into a public .next/static/ chunk or committed to Git history.
Step-by-Step Next.js / React .env Configuration & Hardening Guide
Apply these four concrete safeguards to eliminate silent dotenv truncation, prevent secret leaks, and keep local and production environments synchronized.
1Keep Secrets Unprefixed and Guard Server Modules With server-only
src/lib/stripe.tsInstall the server-only package and import it at the top of any file reading private process.env secrets. If a Client Component accidentally imports it, Next.js aborts the build immediately.
src/lib/stripe.tstypescriptimport 'server-only'; import Stripe from 'stripe'; const secretKey = process.env.STRIPE_SECRET_KEY; if (!secretKey) { throw new Error('Missing server-only STRIPE_SECRET_KEY environment variable'); } export const stripe = new Stripe(secretKey);2Validate Required Next.js Environment Variables With Zod at Boot
src/env.tsValidate both server and NEXT_PUBLIC_ client schemas explicitly so missing keys like RESEND_API_KEY or malformed URLs fail loudly during startup.
src/env.tstypescriptimport { z } from 'zod'; const serverEnvSchema = z.object({ DATABASE_URL: z.string().url(), NEXTAUTH_URL: z.string().url(), NEXTAUTH_SECRET: z.string().min(32), STRIPE_SECRET_KEY: z.string().startsWith('sk_'), }); export const serverEnv = serverEnvSchema.parse(process.env);3Separate .env.local (Git-Ignored) From Sanitized .env.example
.gitignoreVerify .env*.local is ignored in Git while committing a sanitized .env.example generated by the checker above so onboarding teammates always know every required key.
.gitignorebash# Local secrets — NEVER commit .env .env*.local # Safe committed template !.env.example4Audit Built Client Chunks for Accidental Secret Strings
terminalAfter running npm run build, scan .next/static/chunks/ in CI to guarantee zero private prefixes leaked into client bundles.
terminalbashnpm run build grep -rnE "sk_live_|SERVICE_ROLE|BEGIN PRIVATE KEY" .next/static/ || echo "Clean client bundle"
Common Next.js / React .env Pitfalls
Check these three framework-specific traps before deploying updated environment variables to staging or production.
Prefixing Supabase service_role or Stripe Secret Keys With NEXT_PUBLIC_
The Supabase anon key is designed for browsers (with RLS), but NEXT_PUBLIC_SUPABASE_SERVICE_ROLE_KEY bypasses Row Level Security completely and hands full database admin rights to anyone inspecting DevTools Sources.
Expecting NEXT_PUBLIC_ Variables to Change at Docker Runtime Without Rebuilding
Because Next.js replaces process.env.NEXT_PUBLIC_API_URL with a literal string during next build, overriding NEXT_PUBLIC_API_URL in docker-compose.yml has zero effect on Client Components unless you rebuild or read runtime config via a Server Component.
Destructuring process.env Breaking Client Replacement in Next.js
Writing const { NEXT_PUBLIC_SITE_URL } = process.env fails in browser components because Next.js only inlines direct dot-notation expressions like process.env.NEXT_PUBLIC_SITE_URL.
Pair Your Validated .env With Webhook HMAC, Docker Compose & CORS Tools
Now that your environment variables are syntax-clean and leak-free, verify webhook raw-body HMAC signatures, container healthchecks, and browser cross-origin rules:
Fix Stripe webhook signature mismatch in Next.js App Router Route Handlers. Use await request.text() instead of request.json() with timingSafeEqual.
Generate a Docker Compose config for Next.js App Router standalone output with Prisma ORM and PostgreSQL 16 using pg_isready healthchecks and service DNS.
Configure CORS for Next.js App Router Route Handlers serving external SPAs or widgets. Fix 405 OPTIONS preflights, next.config.ts headers, and Vary: Origin.
Frequently Asked Questions
- Which .env file takes precedence in Next.js App Router?
- In production (next start), Next.js loads in descending priority: process.env (OS/host) -> .env.production.local -> .env.local -> .env.production -> .env. During next dev, .env.development.local takes precedence over .env.local.
- Why is process.env.MY_API_KEY undefined in a Next.js "use client" component?
- By design, Next.js strips all non-NEXT_PUBLIC_ variables from client bundles to protect your secrets. Never add NEXT_PUBLIC_ to a secret key; instead, call your external API from a Route Handler (app/api/**/route.ts) or Server Action.
- Does Next.js support variable expansion like $HOST inside .env files?
- Yes. Next.js uses @next/env with dotenv-expand, meaning literal $ signs inside bcrypt hashes or passwords in .env must be escaped as \$ so dotenv-expand does not treat them as empty variables.
- Why did NEXTAUTH_URL=http://localhost:3000 break my production OAuth login?
- Auth.js / NextAuth uses NEXTAUTH_URL to build OAuth redirect_uri callbacks. Leaving http://localhost:3000 in production causes Google/GitHub OAuth to reject the callback URL with redirect_uri_mismatch.
Related Framework .env Guides
Browse all 10 .env guides →Vite + React .env Checker (Fix VITE_ Prefix & Client Bundle Leaks)
Validate Vite and React .env files locally in your browser. Fix undefined import.meta.env keys, REACT_APP_ migration bugs, and VITE_ secret leaks.
Prisma DATABASE_URL & .env Validator (Fix P1013 Special Character Errors)
Fix Prisma P1013 invalid database string errors locally in your browser. Detect unencoded #, @, and ? characters in DATABASE_URL and DIRECT_URL passwords.
Node.js dotenv & Express .env Checker (Fix Quotes, Multiline Keys & NODE_ENV)
Validate Node.js dotenv and native --env-file .env configs in your browser. Fix unquoted # truncation, duplicate keys, multiline PEM keys, and NODE_ENV bugs.
GitHub Actions & POSIX Shell .env Validator (Fix source .env & CI Leaks)
Validate CI/CD and GitHub Actions .env files locally in your browser. Fix POSIX source .env syntax errors, unquoted spaces, and accidental secret exposure.