Environment variables and server-only code
How .env files load, why only NEXT_PUBLIC_ variables reach the browser, and how the server-only package turns an accidental client import into a build error.
Environment variables and server-only code
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- Next.js loads `.env` files into `process.env` on the server, and a variable is only available in the browser if its name starts with `NEXT_PUBLIC_`.
- `NEXT_PUBLIC_` values are inlined into the JavaScript bundle at build time, so changing them later requires a rebuild, and anything you put there is visible to every visitor.
- Non-public variables read from client code come back empty rather than failing loudly, which is why accidentally importing server code into the client is a quiet bug.
- `import "server-only"` at the top of a module makes the build fail if a Client Component imports it; `client-only` does the reverse.
The danger: server code on the client
A module is just a module. Nothing stops a helper that reads a secret, getData() with an Authorization: Bearer ${process.env.API_KEY} header, from being imported into a Client Component by mistake. The import chain can be long and the mistake invisible. Next.js has two defences, one quiet and one loud.
Environment variables
Next.js loads .env files into process.env automatically. The lookup order, stopping at the first match, is:
process.env(the real environment).env.$(NODE_ENV).local.env.local(not checked whenNODE_ENVistest).env.$(NODE_ENV).env
Put machine-specific secrets in .env.local, which the scaffold’s .gitignore already excludes; the docs warn that you almost never want these files in version control. If you use a src/ folder, .env files are still read from the project root, not from src/. Variables can reference each other, as in TWITTER_URL=https://x.com/$TWITTER_USER.
By default, environment variables exist only on the server. Your Server Components, route handlers and Server Functions can read process.env.DB_PASSWORD and never leak it.
NEXT_PUBLIC_: the deliberate leak
Sometimes the browser genuinely needs a value, such as an analytics ID. Prefix the name with NEXT_PUBLIC_ and Next.js inlines it at build time: every process.env.NEXT_PUBLIC_ANALYTICS_ID in your code is replaced with the literal value in the JavaScript sent to the client.
Two consequences:
- It is public. Anyone can read it in the page source. Never put a secret here.
- It is fixed at build time. After
next build, changing the variable does nothing until you rebuild. If you build one Docker image and promote it across environments, every environment shares the build-time value. For per-environment values, read a non-public variable on the server during dynamic rendering instead.
Inlining is also literal: dynamic lookups such as process.env[name] are not replaced.
Why the leak is quiet
A non-prefixed variable read in client code is replaced with an empty string. So if getData() is imported into a Client Component, it does not crash; it runs with Bearer undefined or an empty key and fails somewhere downstream, usually with a confusing 401. The secret is safe, but the bug is hard to find.
server-only: make it loud
Mark the module that must stay on the server:
// lib/secrets.ts
import "server-only";
export async function getSecretData() {
const res = await fetch("https://example.com/api", {
headers: { Authorization: `Bearer ${process.env.API_KEY}` },
});
return res.json();
}
Now if any Client Component imports this module, directly or through other modules, the build fails. I tested this on Next.js 16.4: a Client Component importing lib/secrets.ts made next build fail, naming lib/secrets.ts as importing “server-only” and printing the import trace through the client component. (The message’s wording mentions the Pages Router oddly, but the trace identifies the real cause.)
The companion client-only package works the other way, for modules that touch window or other browser-only globals. The docs say installing the npm packages is optional in Next.js, since it handles those imports internally to give clearer errors, though you may install them if a lint rule flags extraneous dependencies.
Use server-only in files that hold data-access code, secrets and anything calling a private API. It is a cheap guard that turns a silent bug into a build error.
What the video covers
Codevolution’s chapters cover server component patterns, creating server and client components, implementing server-only functions, testing a server-only function in a Client Component, and using the server-only package. That covers the guard half of this lesson, not the .env mechanics or the NEXT_PUBLIC_ rules. For the environment variable side, the only matching Codevolution video is from 2021 and uses the Pages Router; the mechanics it describes (.env.local, the NEXT_PUBLIC_ prefix) have not changed, but treat it as secondary.
Where this fits
You can keep secrets on the server and fail loudly if they leak. Next, third-party components and context providers finishes the group with libraries that assume a browser.
Check yourself
Why must an API secret not be named `NEXT_PUBLIC_API_KEY`?
Anything prefixed with `NEXT_PUBLIC_` is inlined into the JavaScript sent to the browser at build time, so every visitor can read it. Secrets should have no prefix, so they exist only in server code.
What does a Client Component see when it reads `process.env.DB_PASSWORD`?
An empty value. Only `NEXT_PUBLIC_` variables are replaced with their values in the client bundle; others are replaced with an empty string. The bug is quiet, which is why a build-time guard is useful.
What does `import "server-only"` actually do?
It marks a module as server-only. If a Client Component imports it, directly or through other modules, the build fails with an error showing the import chain, so server code cannot leak to the browser by accident.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.