Skip to content
Tutorials Center
My learning

Topics

Lesson 53 of 72 ยท Configuration, Tooling and Testing

Environment Variables and Secrets

Learn how Next.js loads .env files, which variables reach the browser with NEXT_PUBLIC_, what is fixed at build time and how to validate configuration at startup.

Almost every app needs values that change between machines: a database URL on your laptop and a different one in production, an API key for a payment provider, the public address of the site. Hard-coding them is wrong twice over: the code can no longer move between environments, and secrets end up in Git. The standard answer is environment variables, plain strings supplied by the operating system, and Next.js adds a convenient layer on top: it reads .env files for you and decides which values may be shown to the browser.

This lesson covers the files Next.js loads and the order in which they win, the one prefix that exposes a variable to browser code, the difference between values fixed at build time and values read at request time, and how to fail fast when configuration is missing. Real Next.js cannot run on this site, so the configuration and application code below is read-only. The runnable examples are plain Node.js stand-ins that reproduce the rules: each one says what it simplifies.

Three kinds of values

Server secrets Plain names like DATABASE_URL. Never sent to the browser.
Public values Names starting with NEXT_PUBLIC_ are copied into browser code.
Defaults A committed .env file holds safe, non-secret defaults.

The name decides who can read the value.

1 / 2

The .env files

Put a file named .env.local in the project root (next to package.json, not inside app/) and write one KEY=value per line:

Terminal
# .env.local (read-only example)
DATABASE_URL=postgres://app:secret@localhost:5432/shop
STRIPE_SECRET_KEY=sk_test_example
NEXT_PUBLIC_SITE_URL=http://localhost:3000

On the server you read these through process.env:

TSX
// app/api/health/route.ts (read-only)
export async function GET() {
  const hasDatabase = Boolean(process.env.DATABASE_URL);
  return Response.json({ hasDatabase });
}

Everything in process.env is a string or undefined. process.env.PORT is "3000", not 3000, and a missing variable is undefined, not an error. Both facts cause bugs unless you check them, which is why a later section adds validation.

Next.js loads up to five files, depending on the mode (development for next dev, production for next build and next start, test when NODE_ENV is test). It checks them from the highest priority down and the first file that defines a name wins:

Priority File Typically contains
1 Variables already in the process (shell, Docker, host dashboard) Real production secrets
2 .env.development.local, .env.production.local, .env.test.local Private per-mode overrides
3 .env.local (skipped in test mode) Your personal secrets
4 .env.development, .env.production, .env.test Shared per-mode settings
5 .env Shared defaults

The test mode skips .env.local so that tests behave the same on every machine. Files whose names end in .local are meant to stay on one machine. The default .gitignore created by create-next-app ignores .env*, so nothing is committed unless you opt in. A common team rule is: commit a .env.example with fake values so newcomers know which names exist, keep real values in .env.local or in the host's settings.

Inside a file, a value can refer to an earlier one with $NAME, for example DATABASE_URL=postgres://$DB_HOST/shop. If you need a literal dollar sign (in a password, say), escape it as \$.

A stand-in for the loader

The example below imitates the loader. It is not the real @next/env package: the five files are inline strings and the parser handles only the common cases (comments, quotes, $NAME). It does show the real priority rules, so try changing a file and watch which value wins.

Node.js Which value wins? A mini .env loader

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Look at DB_HOST in the four runs. In development and production it comes from .env.local and beats the .env default. In test mode .env.local is skipped, so .env.test wins. In the last run a variable set in the shell beats every file, and because it came from the shell, DB_URL is built from it too. That last rule is how production works: your host or container sets real values, and files only fill the gaps.

NEXT_PUBLIC_: values that reach the browser

By default a variable exists only in server code. Browser code runs on your visitor's computer, so anything shipped there is readable by anyone who opens the developer tools. Next.js therefore refuses to expose a variable unless its name starts with NEXT_PUBLIC_:

TSX
// components/site-link.tsx (read-only)
"use client";

export function SiteLink() {
  // Replaced at build time with the literal string.
  const base = process.env.NEXT_PUBLIC_SITE_URL;
  return <a href={`${base}/about`}>About us</a>;
}

The important word is inlined. During next build, the bundler finds every expression process.env.NEXT_PUBLIC_SITE_URL in code destined for the browser and replaces it with the value at that moment. The built JavaScript contains the text "https://shop.example", not a lookup. Three consequences follow:

  • Changing the variable after the build changes nothing. You must build again.
  • A Docker image built once and promoted from staging to production carries the staging value of every public variable, unless you build per environment.
  • Only the literal form process.env.NEXT_PUBLIC_NAME is found. Dynamic access such as process.env[name], or destructuring const { NEXT_PUBLIC_NAME } = process.env, is not replaced, so it is undefined in the browser.

The stand-in below does the replacement with a regular expression. Real Next.js works on the parsed code, not on text, but the outcome you see is the same.

Node.js Inlining NEXT_PUBLIC_ values at build time

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Only the plain process.env.NEXT_PUBLIC_API line is replaced. The secret is undefined in the browser (good), and so are the dynamic and destructured forms (a bug waiting to happen). The second run shows the third consequence: the value is frozen into the bundle.

Never put a secret behind a NEXT_PUBLIC_ name. An API key that must stay private belongs in a server-only variable used from a Server Action, a Route Handler or a Server Component. Keeping Server Code on the Server shows how the server-only package makes the build fail if such code is imported by mistake.

Build time or request time?

Server code reads process.env while it runs, so you might expect the value to always be current. It depends on when that code runs. A page that is statically generated runs once, during next build, and its HTML contains whatever the variable was then. A page rendered per request, a Route Handler, or a Server Action runs inside the live server and sees the environment of that process.

TSX
// app/status/page.tsx (read-only)
import { connection } from "next/server";

export default async function StatusPage() {
  await connection(); // opt in to rendering on each request
  return <p>Region: {process.env.DEPLOY_REGION}</p>;
}

Without connection() (or another dynamic API such as cookies()), this page may be prerendered at build time and show the build machine's DEPLOY_REGION forever. Static vs Dynamic Rendering explains how Next.js decides. A practical rule for secrets and per-environment settings: read them in code that runs per request, and treat NEXT_PUBLIC_ values as part of the build.

The env key in next.config.ts (see Configuring Next.js) also inlines values at build time, for any name, and it ends up in browser bundles where used. Prefer .env files; reach for the config key only for values computed in the config file itself.

Validate configuration at startup

A forgotten variable is the most boring way to break production, and the error often appears far from the cause (Cannot read properties of undefined, or a database driver complaining about an empty URL). The fix is to describe what you expect once and check it early. Libraries such as Zod are popular for this; the read-only version looks like this:

TSX
// lib/env.ts (read-only)
import "server-only";
import { z } from "zod";

const schema = z.object({
  DATABASE_URL: z.string().startsWith("postgres"),
  SESSION_SECRET: z.string().min(32),
  PORT: z.coerce.number().int().min(1).max(65535).default(3000),
});

export const env = schema.parse(process.env);

Import env instead of touching process.env everywhere. You get types, conversion (PORT becomes a number), and one clear error listing every problem. To fail at server start rather than at the first request that needs the value, import this module from instrumentation.ts, a file whose register() function Next.js runs once when the server boots (covered in Debugging and Error Handling). Keep a separate schema for NEXT_PUBLIC_ values and check it at build time.

The stand-in has no dependencies. It collects all problems before throwing, which is friendlier than stopping at the first.

Node.js A configuration validator that reports every problem

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The first call reports four problems at once, including the missing public URL, and the second shows the parsed result with PORT converted to a number from its default.

Habits that keep secrets safe

  • Commit .env.example (fake values) and never .env.local. If a secret was ever committed, rotate it: deleting the file does not remove it from Git history.
  • Set production values in your host's dashboard, Docker or orchestrator, not in files shipped with the app.
  • Give public values boring names and nothing sensitive. If you must ask yourself whether a value is safe to publish, it should not start with NEXT_PUBLIC_.
  • Do not log process.env or send it to an error tracker.
  • Treat .env files as an input to the build and start commands: restart the dev server after editing them.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which variable can browser code read?

    Only names that start with NEXT_PUBLIC_ are copied into browser bundles. Every other variable stays on the server, even when it sits in the same file.
  2. 2. A file .env.local sets DB_HOST=a, .env sets DB_HOST=b and the shell sets DB_HOST=c. What does the app see in production?

    Real process variables have the highest priority. Next.js only fills in names the process does not already define.
  3. 3. You change NEXT_PUBLIC_API_URL on your host and restart the server, but the browser still calls the old address. Why?

    Public values are replaced with literal strings at build time. Restarting the server cannot change code that was already built.
  4. 4. Why does process.env[name] fail to expose a NEXT_PUBLIC_ value in browser code?

    The build can only replace expressions it can recognise in the source. A computed key is unknown until runtime, when the browser's process.env is empty.

Summary

  • Next.js loads .env, .env.local and per-mode files; variables already in the process win, then more specific files beat general ones, and .env.local is skipped in test mode.
  • Server code reads process.env; every value is a string or undefined.
  • Only names starting with NEXT_PUBLIC_ reach the browser, and they are inlined as literals at build time, so changing them means rebuilding.
  • Static pages read the environment at build time; use per-request rendering for values that differ per deployment.
  • Validate configuration once in a module such as lib/env.ts and import that instead of process.env.
  • Never commit secrets; rotate any that were committed.

Next: TypeScript, ESLint and Typed Routes