Next.js environment variables in Docker: why NEXT_PUBLIC_ gets frozen at build time
You change a variable on the server and the browser still sees the old one. Which variables Next.js reads at build time, which at runtime, and how to organize them.
This blog belongs to CREA.MBA, a Next.js boilerplate with auth, payments and an admin panel already set up. See what's included
You deploy your Next.js app in Docker, change NEXT_PUBLIC_SITE_URL in your platform's dashboard, restart the container, and the browser keeps using the old value. Or the opposite: you add your analytics key, the page doesn't see it, and printenv inside the container shows it just fine.
Docker and Coolify are doing exactly what they should. Next.js handles environment variables in two very different ways depending on their name and where you read them from, and in a container deployment the difference becomes obvious. Let's go step by step.
Two moments: build and runtime
A Next.js app goes through two phases with different environments:
- The build (
next build), where the code is compiled and the JavaScript shipped to the browser is generated. - Runtime (
next start), where the server handles requests.
On Vercel both phases share configuration and you rarely notice. In Docker they're two separate moments, sometimes on different machines, and variables that exist in one don't have to exist in the other.
NEXT_PUBLIC_ is copied verbatim into the bundle
The Next.js docs put it this way: to make a variable available in the browser, Next.js "inlines" its value into the JavaScript at build time, replacing every reference to process.env.NEXT_PUBLIC_... with the literal text. The prefix is what triggers it.
// Your code
initAnalytics(process.env.NEXT_PUBLIC_GA_MEASUREMENT_ID);
// What reaches the browser after the build
initAnalytics("G-ABC123");The consequence, again in the docs' words: after the build, your app no longer responds to changes in those variables. If you build one Docker image and deploy it to several environments, every NEXT_PUBLIC_ keeps the value it had when the image was built.
There are two cases where the replacement doesn't even happen, and your code gets undefined without any warning:
// ❌ Not replaced: the name is dynamic
const key = 'NEXT_PUBLIC_GA_MEASUREMENT_ID';
process.env[key];
// ❌ Not replaced either: read through another variable
const env = process.env;
env.NEXT_PUBLIC_GA_MEASUREMENT_ID;The replacement is textual, so it has to find process.env.NEXT_PUBLIC_WHATEVER written out exactly like that.
Unprefixed variables only exist on the server
Anything without NEXT_PUBLIC_ is only available in the Node.js environment. In the browser, process.env.STRIPE_SECRET_KEY is undefined, which is exactly what you want for a secret.
The trouble starts with code used on both sides. A pattern we've seen in more than one project:
// src/config/env.ts
export const isPolarConfigured = Boolean(process.env.POLAR_ACCESS_TOKEN);'use client';
import { isPolarConfigured } from '@/config/env';
export function PaymentWarning() {
if (isPolarConfigured) return null;
return Payments are not configured;
}On the server, isPolarConfigured is true. In the browser, POLAR_ACCESS_TOKEN doesn't exist and the "payments are not configured" warning always shows, even though payments work. TypeScript doesn't complain and the build passes.
There are three possible fixes, depending on the case:
- Compute it on the server and pass it as a prop. The server component that renders
PaymentWarningchecks the variable and passes it a boolean. The secret never leaves the server. - Expose only what's needed. If the client has to know something, create a public variable that says only that (
NEXT_PUBLIC_PAYMENTS_ENABLED=true), never the key. - Move the component to the server if it doesn't need interactivity.
To stop a module with secrets from being imported by the client by accident, the server-only import makes the build fail if that happens (in Next.js installing the package is optional, per its docs; the framework recognizes the import):
// src/lib/payments/config.ts
import 'server-only';Reading variables at runtime on the server
Unprefixed variables are read when the code runs… as long as the code runs on every request. If the page is rendered statically during the build, process.env.MY_VARIABLE is evaluated at that moment and the result is baked into the HTML.
The Next.js docs suggest marking the component as dynamic before reading the variable:
import { connection } from 'next/server';
export default async function Page() {
await connection();
// From here on, the variable is read on every request
const supportEmail = process.env.SUPPORT_EMAIL;
// ...
}connection() (like reading cookies() or headers()) makes the route render on demand. With that, the same Docker image works across environments with different values.
The same goes for code that runs when a module is imported. If you do const client = new Client(process.env.API_KEY) at the top level and the build imports that module to generate static pages, the variable is read at build time. When the container is built without that variable, the client ends up misconfigured. That's why the CREA.MBA boilerplate's rate limiter resolves REDIS_URL on first use rather than in the constructor: the container is built without it and only receives it at startup.
How to get a NEXT_PUBLIC_ into the build
If a public variable needs to be in the bundle, it has to exist when next build runs.
With your own Dockerfile, declare it as a build argument:
ARG NEXT_PUBLIC_SITE_URL
ENV NEXT_PUBLIC_SITE_URL=$NEXT_PUBLIC_SITE_URL
RUN bun run builddocker build --build-arg NEXT_PUBLIC_SITE_URL=https://yourdomain.com .In Coolify, each environment variable has options to decide whether it's available at build time, at runtime or both. NEXT_PUBLIC_ variables have to be available at build time, and after changing them you have to redeploy; a restart isn't enough. Restarting boots the same container with the same bundle.
The reverse matters too: don't mark secrets as build variables unless you need to. A variable available at build time can end up in the image layers or in the build logs.
And if you really need to change a public value without rebuilding
There are legitimate cases: a single image promoted from staging to production, or a URL that changes per customer. The Next.js docs suggest setting up your own API to serve those values to the client. In practice, with the App Router there's a simpler way: read them in a dynamic server component and pass them down to the client.
// app/layout.tsx (server component)
import { connection } from 'next/server';
import { PublicConfigProvider } from '@/components/public-config';
export default async function RootLayout({ children }: { children: React.ReactNode }) {
await connection();
const config = {
siteUrl: process.env.SITE_URL ?? '',
supportEmail: process.env.SUPPORT_EMAIL ?? '',
};
return (
{children}
);
}The cost is that everything under that layout now renders on demand, so do it in the lowest layout that needs it. And whatever you pass there ends up in the HTML: only values you don't mind anyone seeing.
There are also scripts out there that replace placeholders in the bundle's .js files when the container starts. They work, but they patch the build output on the fly, and we'd rather not depend on that.
A checklist before deploying
- Inventory. List every variable the app uses and tag it: server secret, build-time public, or public that you need to change at runtime.
- No secrets with
NEXT_PUBLIC_. Anything with the prefix is public, no exceptions. A Stripesk_live_key with that prefix is sitting in the JavaScript anyone can download. - No server
process.envinside'use client'. Search for it withgrep. If it shows up, it's anundefinedwaiting to happen. - Public variables available at build time on your platform.
- After changing a public one, redeploy. Restarting doesn't rebuild.
The last point has a case that rarely comes up: Sentry's public DSN has to be in the build for two reasons: the SDK needs it, and the boilerplate uses it to build the Content Security Policy (CSP). Without it, the browser blocks error reports and you never find out about anything.
Takeaways
NEXT_PUBLIC_is copied as text into the bundle duringnext build. Changing it means rebuilding.- Without the prefix, the variable only exists on the server; in a client component it's
undefined. - To read a variable on every request, the route has to be dynamic (
connection(),cookies(),headers()). - If a public value has to change without rebuilding, read it in a server component and pass it down.
We cover self-hosted infrastructure in Hetzner + Coolify as a Vercel alternative. CREA.MBA's .env.example groups variables by service and flags the ones Coolify needs at build time, like the Sentry DSN.
How long did you lose the first time a NEXT_PUBLIC_ wouldn't change?
Enjoyed this article?
Subscribe for more tutorials and tips on building products with AI