How do you set environment variables in Next.js?

Put variables in .env files at the project root. Next.js loads them into process.env automatically. Server code can read any variable, but browser code can only read variables prefixed with NEXT_PUBLIC_, which are inlined at build time.

Files and load order

Next.js looks for these files, and the first match for a variable wins:

  1. process.env (already set in the shell or hosting platform)
  2. .env.$(NODE_ENV).local
  3. .env.local (not loaded when NODE_ENV=test)
  4. .env.$(NODE_ENV) (.env.development, .env.production, .env.test)
  5. .env

Commit .env and .env.development with safe defaults. Never commit .env*.local.

Server vs browser

  • Server-only (DATABASE_URL, STRIPE_SECRET_KEY): read in Server Components, Route Handlers, Server Functions and proxy.ts.
  • Public (NEXT_PUBLIC_API_URL): replaced with the literal value in client bundles at next build. Changing it later requires a rebuild.

Runtime values

Server-side reads happen at request time only for code that runs at request time. If a page is prerendered, process.env is read during the build. To force a runtime read (for example one Docker image across environments), call await connection() before reading. The old publicRuntimeConfig/serverRuntimeConfig were removed in Next.js 16.

Other tips

  • Variables can reference others: API=$HOST/api.
  • Use @next/env's loadEnvConfig to load the same files in scripts or test setup.
  • Validate variables at startup (for example with Zod) so a missing secret fails fast.
  • Import server-only in modules that read secrets so they cannot be bundled for the client.

Code example

tsx
1// .env.local (never commit)
2// DATABASE_URL="postgres://user:pass@localhost:5432/app"
3// NEXT_PUBLIC_SITE_URL="http://localhost:3000"
4
5// lib/env.ts - validate once, fail fast
6import "server-only";
7import { z } from "zod";
8
9export const env = z
10 .object({
11 DATABASE_URL: z.string().url(),
12 NEXT_PUBLIC_SITE_URL: z.string().url(),
13 })
14 .parse(process.env);
15
16// app/status/page.tsx
17import { Suspense } from "react";
18import { connection } from "next/server";
19
20async function Region() {
21 await connection(); // read at request time, not baked in at build
22 return <p>Region: {process.env.DEPLOY_REGION ?? "local"}</p>;
23}
24
25export default function Page() {
26 return (
27 <Suspense fallback={<p>…</p>}>
28 <Region />
29 </Suspense>
30 );
31}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.

Open in study app