Every real application needs configuration that differs between environments and must not be hard-coded: the database connection string, API keys for third-party services, the public URL of the site, feature flags, and secrets for signing sessions. Environment variables are how you supply this configuration from outside your code, so the same codebase runs against a local database in development and a production database in deployment without changing a line. In the App Router, environment variables carry an additional and critical dimension: because your code runs in two places — on the server and, for client components, in the browser — you must be deliberate about which variables are allowed to reach the client, since a secret exposed to the browser is a secret leaked to the world.
This topic is small in surface area but outsized in consequence, because the most common and damaging configuration mistake is leaking a secret to the client, and the framework's rules around this are precise enough to be worth understanding exactly rather than approximately. A database password or API key bundled into client JavaScript is visible to anyone who opens the browser's developer tools, and such leaks are a recurring source of real breaches. Next.js draws a bright line using a naming convention: variables are server-only by default and never sent to the browser unless they carry a specific public prefix, which is an explicit, visible opt-in to exposure. Getting this right means understanding the prefix rule, where variables are loaded from, the difference between build-time and runtime values, and the discipline of keeping secrets out of the client and out of version control. This lesson covers how environment variables are defined and loaded, the server-versus-client exposure rule, and the configuration practices that keep secrets safe across environments.