.env Secret & Syntax Checker · Next.js / React

Next.js .env.local Validator & NEXT_PUBLIC_ Secret Leak Checker

Lint your Next.js / React .env file locally in your browser to catch secret leaks, syntax truncation, and missing .env.example keys. Copy an auto-fixed .env or sanitized template below.

Written & verified by Chathura Prabashana · Updated November 2026

1. Paste .env or load a test scenario2. Inspect live diagnostics3. Copy cleaned config
Quick-Test Scenarios:

1. Source .env Input

.env.example Parity Diff4 matched key(s)
Missing Required Keys:
STRIPE_SECRET_KEYSUPABASE_SERVICE_ROLE_KEYRESEND_API_KEY
Undocumented Keys:
NEXT_PUBLIC_STRIPE_SECRET_KEYNEXT_PUBLIC_SUPABASE_SERVICE_ROLE_KEYNEXT_PUBLIC_DEBUG
NEXT_PUBLIC_SITE_URL=http://localhost:3000
NEXT_PUBLIC_STRIPE_SECRET_KEY=sk_live_demo_placeholder
NEXT_PUBLIC_SUPABASE_SERVICE_ROLE_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9_demo
NEXT_PUBLIC_DEBUG=true
DATABASE_URL="postgresql://app:pass@postgres:5432/app_db"
NEXTAUTH_URL=http://localhost:3000
NEXTAUTH_SECRET="super_secret_value#withhash"
Critical
4
Warnings
7
Valid Keys
1
Missing Keys
3

Line-by-Line Diagnostics

Runs locally in your browser. Pasted .env values are never uploaded or saved to localStorage.

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:

Runtime Exception / Audit Output

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.

  1. 1Keep Secrets Unprefixed and Guard Server Modules With server-only

    src/lib/stripe.ts

    Install 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.tstypescript
    import '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);
  2. 2Validate Required Next.js Environment Variables With Zod at Boot

    src/env.ts

    Validate both server and NEXT_PUBLIC_ client schemas explicitly so missing keys like RESEND_API_KEY or malformed URLs fail loudly during startup.

    src/env.tstypescript
    import { 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);
  3. 3Separate .env.local (Git-Ignored) From Sanitized .env.example

    .gitignore

    Verify .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.example
  4. 4Audit Built Client Chunks for Accidental Secret Strings

    terminal

    After running npm run build, scan .next/static/chunks/ in CI to guarantee zero private prefixes leaked into client bundles.

    terminalbash
    npm 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.

Pitfall 1

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.

Pitfall 2

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.

Pitfall 3

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.

Related Tools

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:

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.
Browse all 10 .env guides →