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:
process.env(already set in the shell or hosting platform).env.$(NODE_ENV).local.env.local(not loaded whenNODE_ENV=test).env.$(NODE_ENV)(.env.development,.env.production,.env.test).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 andproxy.ts. - Public (
NEXT_PUBLIC_API_URL): replaced with the literal value in client bundles atnext 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'sloadEnvConfigto 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-onlyin modules that read secrets so they cannot be bundled for the client.
Code example
1// .env.local (never commit)2// DATABASE_URL="postgres://user:pass@localhost:5432/app"3// NEXT_PUBLIC_SITE_URL="http://localhost:3000"45// lib/env.ts - validate once, fail fast6import "server-only";7import { z } from "zod";89export const env = z10 .object({11 DATABASE_URL: z.string().url(),12 NEXT_PUBLIC_SITE_URL: z.string().url(),13 })14 .parse(process.env);1516// app/status/page.tsx17import { Suspense } from "react";18import { connection } from "next/server";1920async function Region() {21 await connection(); // read at request time, not baked in at build22 return <p>Region: {process.env.DEPLOY_REGION ?? "local"}</p>;23}2425export 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.