EthioDeploy
DocsPricingDomainsBlogToolsChangelog

Blog/Fix deploy errors

NEXT_PUBLIC_ env variables undefined in production: causes and fixes

BS
Brook SolomonPublished November 17, 2026
Share on XShare on LinkedIn
NEXT_PUBLIC_*

THE SHORT ANSWER

A NEXT_PUBLIC_ variable is undefined in production when it wasn't set while next build ran. Next.js replaces every process.env.NEXT_PUBLIC_ reference with a fixed value during the build, so a variable added to the server afterwards changes nothing until you build again. The other usual causes are reading it dynamically (process.env[name] or a copy of process.env), a name without the NEXT_PUBLIC_ prefix in a Client Component, and one Docker image promoted across environments. For values that must change without a rebuild, read them on the server at request time and pass them down.

Why is my NEXT_PUBLIC_ variable undefined in production?

Because Next.js reads it once, during next build. The Next.js docs say it will “inline” the value “at build time, into the js bundle that is delivered to the client, replacing all references to process.env.[variable] with a hard-coded value.” The value comes from the environment where next build runs. If the variable wasn't there, nothing was inlined.

After that the docs are blunt: “your app will no longer respond to changes to these environment variables.” Setting the variable on the server and restarting doesn't help. Only a new build does.

// app/analytics.tsx, what you write
"use client"
const id = process.env.NEXT_PUBLIC_ANALYTICS_ID

// .next/static/chunks/*.js, what ships after the build
const id = "abcdefghijk"

If you came from Vite, this is the same idea with a different prefix. The Vite version has its own post: Vite env variables undefined in production.

Quick checklist

What you seeCauseFix
Works locally, undefined after deployThe value lives in .env.local, which isn't in git, so the build machine never had itSet it in your host's settings, then rebuild
You added or changed the variable, nothing changedThe old build still holds the old valueRedeploy so next build runs again
Undefined even though it's set at build timeRead as process.env[name] or through a copy of process.envWrite out process.env.NEXT_PUBLIC_NAME in full
Empty in a Client Component, fine on the serverThe name has no NEXT_PUBLIC_ prefixRename it, or read it in a Server Component and pass it down
Staging and production show the same valueOne Docker image built once and promotedBuild per environment, or read the value at runtime
Undefined only in a Docker buildNo ARG for it in the stage that runs next buildDeclare ARG in that stage and pass --build-arg

Was the variable set when next build ran?

The machine that runs next build needs the variable. This is where most cases end. A few details decide whether the build sees it:

  • The create-next-app template adds all .env files to .gitignore. Whatever you keep in .env.local exists on your laptop and nowhere else, so a CI runner or a hosting platform builds without it.
  • Next.js looks a variable up in this order and stops at the first hit: process.env, .env.$(NODE_ENV).local, .env.local, .env.$(NODE_ENV), .env. A variable set in your host's settings is in process.env, so it wins over every file.
  • If NODE_ENV isn't set, next build runs with production, so it reads .env.production and never .env.development.
  • With NODE_ENV=test, .env.local isn't loaded at all, so test runs can miss a value your dev server has.
  • With a src/ folder, the .env files still belong in the project root. Next.js doesn't load them from src/.

Check the name too. process.env.NEXT_PUBLIC_API_URL and a variable called NEXT_PUBLIC_API_URI are two different variables, and only an exact match gets inlined.

Does the name start with NEXT_PUBLIC_?

Without the prefix, a variable only exists on the server. Next.js keeps it out of the browser on purpose, so a database password never ends up in client JavaScript. The Server and Client Components docs put it this way: “only environment variables prefixed with NEXT_PUBLIC_ are included in the client bundle. If variables are not prefixed, Next.js replaces them with an empty string.”

// app/ui/map.tsx
"use client"

export function Map() {
  process.env.NEXT_PUBLIC_MAPS_KEY // inlined at build time
  process.env.MAPS_KEY            // empty in the browser
}

So the same code can print a value during server rendering and nothing once it runs in the browser. If the value really is public, rename it. If it's a secret, keep it unprefixed and use it only in server code; the server-only package turns an accidental import from a Client Component into a build error.

Are you reading it with a variable or destructuring?

Inlining is a find-and-replace on the exact text process.env.NEXT_PUBLIC_SOMETHING. Anything the build can't see as that text stays unreplaced. The docs give two examples that are not inlined:

// This will NOT be inlined, because it uses a variable
const varName = 'NEXT_PUBLIC_ANALYTICS_ID'
setupAnalyticsService(process.env[varName])

// This will NOT be inlined, because it uses a variable
const env = process.env
setupAnalyticsService(env.NEXT_PUBLIC_ANALYTICS_ID)

Destructuring has the same problem. A config helper like getEnv("NEXT_PUBLIC_API_URL") or a const { NEXT_PUBLIC_API_URL } = process.env line looks tidy and breaks in the browser. If you want one place for your config, spell every variable out in full there:

// lib/public-env.ts
export const publicEnv = {
  apiUrl: process.env.NEXT_PUBLIC_API_URL,
  analyticsId: process.env.NEXT_PUBLIC_ANALYTICS_ID,
}

Are you building one Docker image for every environment?

Then every environment gets the values from the build. The docs say so directly: “if you build and deploy a single Docker image to multiple environments, all NEXT_PUBLIC_ variables will be frozen with the value evaluated at build time.” docker run -e NEXT_PUBLIC_API_URL=... reaches the server process, but the browser bundle was written before the container existed.

If you build per environment, pass the value as a build argument. Docker build arguments don't cross stages on their own: each stage that needs one declares it with ARG, and every RUN after that sees it as an environment variable. The official with-docker example declares no ARG for app variables, so add them to the builder stage, before next build:

FROM node:24-slim AS builder
WORKDIR /app
COPY --from=dependencies /app/node_modules ./node_modules
COPY . .

ARG NEXT_PUBLIC_API_URL
ENV NEXT_PUBLIC_API_URL=$NEXT_PUBLIC_API_URL

ENV NODE_ENV=production
RUN npm run build
docker build --build-arg NEXT_PUBLIC_API_URL=https://api.example.com .

The runner stage copies .next/standalone and .next/static from the builder, and the client JavaScript in .next/static already holds the value. output: "standalone" changes how the server is packaged, not when NEXT_PUBLIC_ values are read.

Don't pass secrets this way. Docker's docs warn that build arguments are visible in docker history. A NEXT_PUBLIC_ value ends up in public JavaScript anyway, so this only matters for the other variables.

How do I change a public value without rebuilding?

Don't give it the NEXT_PUBLIC_ prefix. Read it on the server while handling the request, and hand it to the browser yourself. The Next.js docs say you can “safely read environment variables on the server during dynamic rendering”, and that this lets you use “a singular Docker image that can be promoted through multiple environments with different values.”

The simplest version reads the variable in a Server Component and passes it to a Client Component as a prop. await connection() makes the page wait for a real request, so the value isn't captured once at build time:

// app/page.tsx (Server Component)
import { connection } from "next/server"
import { Checkout } from "./checkout"

export default async function Page() {
  await connection()
  return <Checkout apiUrl={process.env.API_URL ?? ""} />
}

// app/checkout.tsx
"use client"
export function Checkout({ apiUrl }: { apiUrl: string }) {
  // apiUrl is whatever API_URL is on the running server
}

Props passed to a Client Component must be serializable, so pass strings and plain objects. Only pass values that are meant to be public: anything you put in a prop reaches the browser.

The other option is the one the docs suggest for the frozen case: “set up your own API to provide them to the client.” A Route Handler works. GET handlers have been dynamic by default since Next.js 15, so it reads the variable on every request:

// app/api/config/route.ts
export async function GET() {
  return Response.json({
    apiUrl: process.env.API_URL,
    analyticsId: process.env.ANALYTICS_ID,
  })
}

On older apps you may have used publicRuntimeConfig for this. Next.js 16 removed both serverRuntimeConfig and publicRuntimeConfig; the upgrade guide points to environment variables instead, read at runtime after connection().

What about next.config, proxy.ts and server pages?

  • The env key in next.config is marked Legacy in the docs. Anything listed there is “always included in the JavaScript bundle”, whatever its name, and replaced at build time. The same page says destructuring process.env won't work with it. Don't use it to pass secrets, and don't expect it to pick up values at runtime.
  • proxy.ts (the new name for middleware.ts) runs on the Node.js runtime in Next.js 16 and can't be switched to Edge. A file still named middleware.ts can keep the Edge runtime, and the Edge runtime docs say process.env is available there “for both next dev and next build.”
  • A Server Component prints an old value. Then that page was prerendered at build time. Call await connection() (or use cookies or headers) before reading process.env so it's read per request.

What happens on EthioDeploy?

Project environment variables are available both while the app builds and while it runs, so a NEXT_PUBLIC_ value set in the dashboard is there when next build runs. To fix an undefined one:

  1. Open the project, go to Environment Variables and add the variable with its full NEXT_PUBLIC_ name.
  2. Leave “Runtime only” off. Runtime-only variables are kept out of the build and only handed to the running container, so a NEXT_PUBLIC_ value marked that way never reaches the browser. The dashboard suggests runtime only for keys that look like secrets, but never for a NEXT_PUBLIC_ name.
  3. Redeploy. A new or changed value takes effect on the next build, not on a restart.

Without a Dockerfile there's nothing else to do: Next.js is detected, the variables are passed to the build, and standalone output is handled for you. If your repo has its own Dockerfile, we build that instead and pass every build-time variable as a --build-arg. Your Dockerfile only sees the ones it declares with ARG, so add an ARG line for each NEXT_PUBLIC_ variable in the stage that runs next build, as in the example above. Names that aren't valid build-arg names, and a few reserved ones like PATH, HOSTNAME and NODE_ENV, are skipped, and the build log lists them.

More in Deploy a Next.js app and Environment variables.

Questions

No. Next.js writes the value into the JavaScript bundle during next build, and the docs say the app no longer responds to changes after that. For values that must change without a rebuild, drop the prefix, read the variable on the server during dynamic rendering, and pass it to the browser as a prop or from a Route Handler.

The server reads process.env when it runs, but the browser only gets what was inlined at build time. If the variable wasn't set during next build, or the code reads it as process.env[name] or through a copy of process.env, nothing was inlined and the browser sees no value.

Yes, unless NODE_ENV is test. But create-next-app puts .env files in .gitignore, so .env.local exists on your laptop and not on a CI runner or hosting platform. Set the same variables in your host's settings; variables already in process.env win over every .env file.

Declare each one with ARG in the build stage that runs next build, copy it to ENV if you like, and pass it with docker build --build-arg. Setting it with docker run -e is too late for the browser bundle, because the image already holds the built JavaScript.

Only if the key is meant to be public. NEXT_PUBLIC_ values are inlined into the JavaScript your visitors download, so anyone can read them. Keep secret keys unprefixed and use them only in server code such as Server Components, Route Handlers and Server Actions.

Sources

Checked on November 17, 2026:

  • Next.js: How to use environment variables
  • Next.js: How to self-host your app (environment variables)
  • Next.js: Server and Client Components
  • Next.js: next.config.js env (legacy)
  • Next.js: next.config.js output
  • Next.js: Upgrading to version 16
  • Next.js: proxy.js
  • Next.js: Edge Runtime
  • Next.js: route.js
  • Next.js: with-docker example Dockerfile
  • Docker: Build variables
  • Docker: Dockerfile reference, ARG

Push a repo. Get a URL.

  • Deploy a Next.js app
  • Environment variables on EthioDeploy
  • Vite env variables undefined in production
Start free

Join the EthioDeploy Telegram

Release notes as they ship, plus deploy help from the team and other developers.

Join on Telegram
BS
WRITTEN BYBrook SolomonFounder, EthioDeploy

Brook Solomon founded EthioDeploy and builds its deploy pipeline, build servers and AI coding agent. The posts here come from errors seen in real deploys on the platform.

All posts by Brook →
On this page
  • Why is my NEXT_PUBLIC_ variable undefined in production?
  • Quick checklist
  • Was the variable set when next build ran?
  • Does the name start with NEXT_PUBLIC_?
  • Are you reading it with a variable or destructuring?
  • Are you building one Docker image for every environment?
  • How do I change a public value without rebuilding?
  • What about next.config, proxy.ts and server pages?
  • What happens on EthioDeploy?
  • Questions
  • Sources
0% read

Keep reading

  • 53300

    Fix deploy errorsNov 17, 2026

    Postgres "too many connections" after deploy: how to fix it

    Postgres refuses new connections with "FATAL: sorry, too many clients already" (SQLSTATE 53300, too_many_connections) once every slot under max_connections is taken, and max_connections defaults to 100. After a deploy the usual cause is arithmetic: each process of your app opens its own pool (10 for node-postgres and Prisma 7, 15 for SQLAlchemy), you run several processes, and for a short time the old and the new copy of the app are both connected. Count connections in pg_stat_activity, make copies × processes × pool max fit under the limit with room to spare, release clients you check out, set idle_in_transaction_session_timeout, and put PgBouncer in front when the numbers can't fit.

  • Invalid HTTP_HOST header

    Fix deploy errorsNov 15, 2026

    Django DisallowedHost and CSRF errors behind a proxy

    DisallowedHost means the request's Host header isn't in ALLOWED_HOSTS, so Django answers 400; add your production domain to the list. The CSRF 403 "Origin checking failed - https://... does not match any trusted origins" usually means Django thinks the request came over plain HTTP: the proxy ended HTTPS and forwarded it as HTTP, so Django expects an http:// origin and the browser sent https://. Set SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https") when your proxy sets that header. Since Django 4.0, entries in CSRF_TRUSTED_ORIGINS must include the scheme, such as https://example.com.

  • npm error code ERESOLVE

    Fix deploy errorsNov 15, 2026

    npm ERESOLVE peer dependency error on deploy

    ERESOLVE means a package's peerDependencies range doesn't accept the version your project already uses, and npm 7 and later refuse to build that tree. It often passes locally because your package-lock.json was made with --legacy-peer-deps, your ~/.npmrc sets legacy-peer-deps=true, or your local npm is older, while the build server runs a clean npm ci without any of that. Fix it by upgrading the package to a version whose peer range fits, by forcing the version with overrides in package.json, or, as a last resort, by committing legacy-peer-deps=true in a project .npmrc so every install, local and on deploy, resolves the same way.

EthioDeploy

Agentic first development and deployment, started in Ethiopia, built for developers everywhere.

Telegram community
Product
PricingAI coding agentAgent mode docsDomainsCLIFree backend hostingHosting in EthiopiaChangelog
Deploy guides
Next.jsNode.jsPythonSvelteKitTanStack StartAstroNuxtReact RouterHonoStrapiDjangoFastAPIFlaskStreamlitExpressNestJSLaravelRailsGoTelegram botDiscord botLovableBoltReplitv0Google AI StudioBase44Firebase StudioClaude Code & Cursor
Compare
vs Herokuvs Vercelvs Rendervs Railwayvs Fly.iovs Netlifyvs KoyebHeroku alternativesVercel alternativesNetlify alternativesRender alternativesRailway alternativesFly.io alternativesReplit alternativesPythonAnywhere alternativesDigitalOcean App Platform alternativesGlitch alternatives
Resources
DocsBlogFree toolsAboutSupportContactllms.txt
© 2026 EthioDeployPay by card in USD or bank transfer in ETBTermsPrivacy