Troubleshooting guide

Environment variables missing or exposed in production: fixes

The app runs on your machine. In production, a setting is missing, empty, stale or readable by anyone who opens the browser's network tab. In our data this pattern ranks 3 of 7 by size, with 120 verified cases.

120 verified cases15 min read Updated 23 Nov 2026Fix it with GemmeinHow we collect cases

What you'll see

  • A variable is set in your local .env file and reads undefined or empty on the deployed site.
  • Every email or form submission fails after launch, because a bot-check or provider secret is empty in production.
  • Stripe or another provider's webhook returns 400, 401 or 503 in production while it worked in test mode.
  • A key you meant to keep on the server shows up when you search the JavaScript files the browser downloads.
  • Browser data requests fail with a CORS error on the production origin only.
  • The custom domain shows a certificate warning, a redirect loop, a 421 or a stalled download, while the platform's default URL for the same deployment works.
  • Uptime checks fail all day because a login screen is served instead of your page.

Why it happens

Cause 1

The variable exists in one place, not in the environment you deployed to

A .env file on your laptop is not read by your host. Hosts scope variables per environment, such as Production, Preview and Development on Vercel, and Vercel states that changes apply only to new deployments, not to ones already running. A value added after the last deploy, or added to Preview but not Production, is absent. An empty string passes a naive existence check and fails on the first real request.

Cause 2

Build-time inlining turns a server value into public text

Next.js replaces every reference to a NEXT_PUBLIC_ variable with the literal value at next build and ships it in the JavaScript sent to the browser. Prefixing a secret with NEXT_PUBLIC_ publishes it. The same inlining freezes the value: the Next.js docs say a built app no longer responds to changes in these variables, so a wrong value at build time stays wrong until you rebuild. A shared module that holds server settings and is imported from client code is bundled with everything it contains.

Cause 3

Webhook and API secrets are per endpoint and per environment

Stripe's docs name a wrong endpoint secret as the most common cause of signature failures, and note that the secret printed by the CLI differs from the one on a Dashboard endpoint. Test and live endpoints each have their own. The request body must also reach the verifier unmodified, so a JSON parser that runs first breaks verification even with the right secret.

Cause 4

Hostnames are listed in several unconnected places

The CORS allowlist, the OAuth redirect list, the certificate, the DNS records and the host's domain settings each name the origins separately. If you add a domain in one and miss another, requests from the new origin fail while the default host keeps working. Protection settings can differ by hostname too: on Vercel, Standard Protection leaves production domains open, while All Deployments protects them and the generated URLs, and visitors and monitors then get an authentication screen.

Cause 5

Certificates renew through a validation step nobody watches

Cloudflare's docs say that if domain control validation is not completed, the certificate authority cannot issue or renew the certificate and visitors see SSL/TLS errors. With a partial DNS setup, automatic validation works only when every hostname is proxied and the method is HTTP, and wildcard certificates need a TXT record per hostname. Repeated failed attempts then hit certificate authority rate limits, which keep a certificate from issuing for a while even after the record is fixed.

How to fix it

  1. Validate required settings at boot and fail the deploy

    List every variable the app needs, reject missing and whitespace-only values, and run this from your build command so a bad deploy fails before it goes live. Check the values the live code reads, not only that the name exists.

    const required = ["DATABASE_URL", "STRIPE_SECRET_KEY", "STRIPE_WEBHOOK_SECRET", "TURNSTILE_SECRET"];
    const bad = required.filter((k) => !process.env[k]?.trim());
    if (bad.length) throw new Error(`Missing or empty: ${bad.join(", ")}`);
  2. Set each variable for the right environment, then redeploy

    In the host's dashboard, tick Production for every variable production needs. Because changes reach only new deployments, trigger a fresh build after every edit. Set framework variables that the browser reads before the build runs, since they are frozen into the bundle.

  3. Keep server secrets out of the browser bundle, and scan the output

    Use a client-exposed prefix such as NEXT_PUBLIC_ only for values that are meant to be public, and read secrets in server code, route handlers or functions. Then search the built files for key shapes and fail the pipeline on a match.

    if grep -rEl 'sk_(live|test)_|whsec_' .next/static dist build 2>/dev/null; then
      echo "secret found in client bundle"; exit 1
    fi
  4. Keep one list of every origin and use it everywhere

    Derive the CORS allowlist, redirect URIs and trusted hosts from one list. When requests carry credentials, reply with the specific origin, not a wildcard, and add Vary: Origin when the value changes per request. Answer the OPTIONS preflight with the allowed methods and headers.

    const allowed = new Set(["https://www.example.com", "https://app.example.com"]);
    
    function applyCors(req: Request, headers: Headers) {
      const origin = req.headers.get("origin");
      if (origin && allowed.has(origin)) {
        headers.set("Access-Control-Allow-Origin", origin);
        headers.append("Vary", "Origin");
      }
    }
  5. Test every hostname the way a visitor or monitor reaches it

    Compare the default host with the custom domain, and read the certificate the custom domain serves. If the custom domain loops, check whether the origin redirects to HTTPS while the CDN talks to it over HTTP. Cloudflare's Flexible mode with an HTTPS redirect at the origin causes this loop, and Full or Full (strict) fixes it. For monitors blocked by deployment protection, use the host's bypass for automation instead of switching protection off. If the domain should receive mail, also confirm it has an MX record.

    curl -sI https://my-app.vercel.app | head -5
    curl -sI https://www.example.com | head -5
    openssl s_client -connect www.example.com:443 -servername www.example.com </dev/null 2>/dev/null | openssl x509 -noout -subject -dates
    dig +short MX example.com
  6. Fix validation before you retry certificate issuance

    Let's Encrypt allows 5 authorization failures per identifier per account per hour, 5 certificates per exact set of names per 7 days, and 50 per registered domain per 7 days. Repeated retries against a broken challenge record use up those limits. Correct the DNS record or validation method first, then retry once.

  7. Rehearse a rotation before you need one

    For each secret, add the new value, deploy, confirm traffic works, then revoke the old one. Stripe lets you roll an endpoint secret and keep the old one valid for up to 7 days, so both are accepted while you update the server. Run the same drill for your email provider key, since a disabled key stops all sends at once.

Check it's fixed

  • Deploy with one required variable deliberately removed. The build should fail with the variable's name, and the live site should keep serving the previous version.
  • Run the bundle scan against a fresh production build and confirm it exits clean. Then add a fake key string to a client file and confirm the scan fails.
  • Send a real request from each production origin and confirm the response carries Access-Control-Allow-Origin with that exact origin.
  • Replay a test webhook against the production endpoint and confirm it returns 2xx. Roll the secret once and confirm deliveries still succeed during the overlap.
  • Fetch the custom domain and the default host with curl and confirm both return the same status and body length, with a certificate that is valid for the custom name.

Fix it with Gemmein

A publish can fail at its secret_scan step, and a relay secret already on the same-named relay in the other environment is refused, so Development and Live keep their own. A Live relay or Function waiting on a secret stays paused until it is set, and a browser call with the Live key from an address that is not a verified domain is refused with 403 origin_not_allowed, naming the address.

  1. Read what the publish flagged

    A publish can stop as FAILED at its secret_scan step, naming the file and line when known, the reason and the fix, and to investigate a failed publish npx gemmein site log leads each failure with its step, the file and line, the reason and the fix. Other things to check, such as a key the page shouldn't send, are listed under the PUBLISHED answer, and your human sees each publish's result on the Site page.

    npx gemmein site log
  2. Give each relay its signing secret

    The signature and shared_token schemes start with a secret Gemmein makes, shown at create (where the sender lets you set the secret, prefer letting Gemmein make it); stripe, svix and the public-key recipes start with nothing, and the sender's secret is pasted on the relay's page or piped in on stdin (Development only). While no secret is stored yet, every event answers 401 bad_signature, and a key already on the same-named relay in the other environment is refused with 400 invalid_input.

    printf '%s' "$SECRET" | npx gemmein relays secret <name>
  3. Set what Live is waiting for

    A relay carried into Live that is waiting on a secret is paused with exactly what is missing, and when sync (or the Relays page) sets that secret, the pause lifts by itself. A Function reaches Live with its secrets' names, never their values, and waits paused until every secret's value is set there too.

  4. Verify the domains your Live app is called from

    Live accepts only the domains on the Domains page that are verified; a browser call with the Live key from another address is refused 403 origin_not_allowed, naming the address, and Errors lists such addresses. Once a domain is chosen to show your Live site, proven yours and a version is live, a CNAME to your app's Live address shows the site there, and while it is Connecting… Gemmein checks it on its own every 10 minutes and sets up the secure connection (https).

    npx gemmein domains

Specific fixes

Stuck on one exact error? These pages go deeper on one symptom each.

Questions

Why is a variable undefined in production when it works locally?

Your host does not read your local .env file. Set the variable in the host's dashboard for the Production environment, then redeploy, because Vercel applies changes only to new deployments. For browser-side variables in Next.js, also set it before the build, since the value is inlined at build time.


Is it safe to put an API key in a NEXT_PUBLIC_ variable?

No. Next.js inlines these variables into the JavaScript it sends to the browser, so anyone can read the value. Use the prefix only for values meant to be public, and keep secrets in server-side code.


Why does the default platform URL work but my custom domain does not?

They sit on separate layers. DNS, certificate, proxy or CDN settings, redirect rules and protection settings can differ between the two. Compare both with curl and read the certificate the custom domain serves before changing application code.


Why does Stripe say webhook signature verification failed in production?

Stripe lists the wrong endpoint secret as the most common cause. Test and live endpoints have separate whsec_ secrets, and a CLI secret differs from a Dashboard endpoint's. A body parser that changes the raw request body before verification causes the same error.


My certificate will not renew and issuance is rate limited. What now?

Fix the validation record or method first. Let's Encrypt limits failed authorizations to 5 per identifier per account per hour, and issuance to 5 duplicate certificates and 50 per registered domain per 7 days. Retrying before you fix the cause extends the wait.


Sources

← Back to the full report