The boundary you've studied depends on import statements, and an import is easy to write without thinking. The editor adds it for you, someone marks a component with 'use client' as a quick fix, and a module with queries or keys ends up in the browser. Often without any error: the page keeps working.
This lesson sets up barriers that fail at build time, before the slip reaches anyone. You'll see server-only and client-only, the paths through which a secret leaks and how to close them, and configuration through environment variables: where they come from, in what order they're read, when their value is fixed and how to check at startup that they're correct. AgendaViva will be ready to receive its first key in module 4, the database one.
- Environment poisoning
A module without a directive can be imported from both sides. That's an advantage for lib/format.ts and a risk for lib/data/events.ts. Suppose someone needs the page size in a client component:
They asked for a constant and dragged in the module. With it can come the queries, the in-memory data and, in 04-02, the database client. Bundlers remove what isn't used, but that's not a guarantee to build security on. There are three possible kinds of damage:
| Damage | Example |
|---|---|
| Internal logic is published | A rule for detecting fraudulent bookings |
| Data is published | The events array, including those under review |
| It fails in the browser | A Node module that doesn't exist there, or a key that arrives empty |
The third is the most puzzling: the function runs in the browser without its configuration and returns a permissions error that seems to come from somewhere else.
- server-only and client-only
server-only is a marker you import for its side effect:
// lib/data/events.ts
import 'server-only'
import { events, venues, simulateQuery } from '@/lib/data/memory'
// …If that module ends up in the client graph, directly or through other modules, the build fails with a message like 'server-only' cannot be imported from a Client Component module, and the import trace lets you see how it got there.
The opposite marker is client-only, for modules that use window and make no sense in a Server Component. It's a good fit for favorites:
Four clarifications:
- You don't need to install anything. Next.js recognizes both names and doesn't use the contents of the npm packages. You only install them if some linter rule requires it.
client-onlydoesn't prevent prerendering. Client Components that import the module still run on the server to generate HTML. What it forbids is importing it from a Server Component.'use client'andclient-onlyaren't the same. The directive creates a boundary the server can import; the marker forbids it from doing so.- It protects code, not data. A Server Component can call a protected function and pass its result as a prop. That's still your responsibility (03-03).
Only Next.js understands the marker. A Node script, the migrations tool or tests that import the module outside of it won't find the package, or will get an error. We'll take that into account in 04-02, where the database schema will go in a module without the marker, and in 10-03, when configuring Vitest.
2.1. Which AgendaViva modules get it
| Module | Marker | Reason |
|---|---|---|
lib/data/memory.ts |
server-only |
Contains the data, including unpublished events |
lib/data/events.ts, venues.ts, dashboard.ts |
server-only |
Queries |
lib/env.ts (section 5) |
server-only |
Configuration |
lib/favorites.ts |
client-only |
localStorage |
lib/types.ts, format.ts, filters.ts, site.ts, theme.ts |
None | They work on both sides |
Components with 'use client' |
None | They already declare their side |
| Server Components | None, unless they contain sensitive logic |
Add the markers. The rule going forward: everything created in lib/data/ starts with import 'server-only'. Check that it works: temporarily import EVENTS_PER_PAGE in favorite-button.tsx and run npm run build. You'll see the error; undo the change.
import type statements aren't affected. import type { Occupancy } from '@/lib/data/dashboard' disappears at build time, so a Client Component can use the types from a server module. If the constant were needed on the client, it would move to a neutral module.
- Environment variables
Configuration that changes between your machine, testing and production, and above all secrets, isn't written in the code. Next.js reads the .env* files at the project root and loads them into process.env:
# .env.local
MAX_SPOTS_PER_BOOKING=4
SITE_NOTICE="Maintenance on Monday from 6:00 to 7:00 a.m."
NEXT_PUBLIC_SITE_URL=http://localhost:3000All values are strings: MAX_SPOTS_PER_BOOKING is '4'. Inside the file you can reference another variable with $NAME; if a value contains a literal $, as can happen in a password, write it as \$.
3.1. The files and their order
Each variable is looked up in this order, and the first one found wins:
| Order | Source | What it's for |
|---|---|---|
| 1 | The system's process.env |
Production: whatever the platform or container defines |
| 2 | .env.development.local or .env.production.local |
Values specific to your machine for one environment |
| 3 | .env.local |
Values specific to your machine; not read with NODE_ENV=test |
| 4 | .env.development or .env.production |
Defaults for one environment |
| 5 | .env |
General defaults |
next dev uses the development environment; the other commands, production, unless NODE_ENV is already set. Note that .env.local is also read at build time on your machine: if you run npm run build with a development address in there, it ends up in the output.
If you change a .env file and don't see the effect, restart npm run dev.
3.2. What goes into the repository
The .gitignore from create-next-app excludes .env*, that is, all of them. That's the safe default. So that the team knows which variables exist, you version a template without secrets:
# .env.example
# Spots a person can request in one booking (between 1 and 20)
MAX_SPOTS_PER_BOOKING=4
# Notice on the public site; empty if there isn't one
SITE_NOTICE=
# Public address; fixed at build time
NEXT_PUBLIC_SITE_URL=http://localhost:3000Without that exception, the template would be ignored too. Whoever joins the project copies the file as .env.local and fills it in. If a secret ever makes it into the repository, deleting it isn't enough, because it stays in the history: you have to rotate it in the service that issued it.
- NEXT_PUBLIC_: what gets published
By default, variables only exist on the server. Their value doesn't reach client code. Those starting with NEXT_PUBLIC_ are the exception, and their mechanism is peculiar: at build time, Next.js replaces every process.env.NEXT_PUBLIC_X in the code with its value, as if you'd typed it by hand.
// lib/site.ts
export const SITE_NAME = 'AgendaViva'
export const SITE_URL = process.env.NEXT_PUBLIC_SITE_URL ?? 'http://localhost:3000'That replacement has three consequences:
- It's public. Anyone can read it in the downloaded JavaScript. The prefix is a decision to publish; a secret never has it.
- It's fixed at build time. Changing it on the server and restarting does nothing. If you build once and deploy the output to staging and production, both will have the build's value. You have to build per environment or use another route (section 6).
- It must be written out in full. The replacement is textual, so indirect forms don't work on the client:
// These aren't replaced
const name = 'NEXT_PUBLIC_SITE_URL'
const a = process.env[name]
const env = process.env
const b = env.NEXT_PUBLIC_SITE_URLWe'll use it in ShareButton, to share the event page's official address without tracking parameters. In the handler, replace the url line and import SITE_URL:
SITE_URL lives in a neutral module, and in 09-03 the metadata will use it too. This button is a good reminder of the second consequence: if you build without defining the variable, production will share links to localhost.
You'll come across projects with an env key in next.config.ts. It's an older mechanism that always includes the value in the JavaScript, prefix or no prefix. Don't use it.
- Validating the environment at startup
process.env.WHATEVER is string | undefined, and a misspelled name doesn't produce any error: it yields undefined and the failure shows up far away, on the first booking. It's a good idea to read the environment in a single module that converts, validates and gives proper names.
// lib/env.ts
import 'server-only'
export interface Env {
siteNotice: string | null
maxSpotsPerBooking: number
}
function readInteger(
name: string,
options: { defaultValue: number; min: number; max: number },
): number {
const text = process.env[name]?.trim()
if (!text) return options.defaultValue
const value = Number(text)
if (!Number.isInteger(value) || value < options.min || value > options.max) {
throw new Error(
`The variable ${name} must be an integer between ${options.min} and ${options.max}`,
)
}
return value
}
export function readEnv(): Env {
return {
siteNotice: process.env.SITE_NOTICE?.trim() || null,
maxSpotsPerBooking: readInteger('MAX_SPOTS_PER_BOOKING', {
defaultValue: 4,
min: 1,
max: 20,
}),
}
}process.env[name]is valid here because the module is server-only and reads real variables, with no replacement.- The message names the variable, but doesn't show its value. With a secret, including it would leave it in the logs.
- It's a function, not a precomputed object. If it were evaluated on import,
next buildwould require having every value, including production secrets, on the machine that builds. - The rest of the code calls
readEnv(). That wayprocess.envisn't scattered around: it stays in this module, inlib/site.tsfor the public value and in the startup file you'll see next.
The validation is deliberately minimal. When there are more variables, it can be replaced by a Zod schema, the library from 06-03.
What's missing is running it early. Next.js calls the register function in instrumentation.ts, at the project root, once when a server instance starts and before it handles any requests:
// instrumentation.ts
export async function register() {
if (process.env.NEXT_RUNTIME === 'nodejs') {
const { readEnv } = await import('@/lib/env')
readEnv()
}
}If the configuration is wrong, the error shows up at startup and in the terminal, not on a visitor's screen. The NEXT_RUNTIME check is there because register is invoked in every runtime. The file has more uses, which you'll see in 10-05.
Try it with MAX_SPOTS_PER_BOOKING=lots.
- Values read on every request
Server variables aren't replaced: they're read when the code runs. The question, then, is when it runs. With Cache Components, whatever doesn't wait for anything runs at build time and goes into the shell. Reading process.env is a synchronous operation, so this component would freeze the notice from the machine that builds:
// The value ends up in the shell, at build time
export function SiteNotice() {
const { siteNotice } = readEnv()
return siteNotice ? <p>{siteNotice}</p> : null
}To read it at runtime you have to take it out of prerendering. The environment variables documentation does this with connection(), and the io() documentation recommends preferring the latter with Cache Components. You already use it in simulateQuery:
// components/site-notice.tsx
import { io } from 'next/cache'
import { readEnv } from '@/lib/env'
export async function SiteNotice() {
await io()
const { siteNotice } = readEnv()
if (!siteNotice) return null
return (
<p role="status" className="bg-amber-100 px-4 py-2 text-center text-amber-950">
{siteNotice}
</p>
)
}// app/(public)/layout.tsx (imports Suspense and SiteNotice)
export default function PublicLayout({ children }: LayoutProps<'/'>) {
return (
<>
<Suspense fallback={null}>
<SiteNotice />
</Suspense>
<Header />
<main className="mx-auto w-full max-w-5xl flex-1 px-4 py-8">{children}</main>
<Footer />
</>
)
}The <Suspense> is required: whatever follows io() stays out of the shell. The notice arrives a little after the header and pushes it down; that's acceptable for an exceptional message, but it wouldn't be for a permanent one.
| How it's read | When it's fixed | Changes when the server restarts |
|---|---|---|
NEXT_PUBLIC_X, anywhere |
At build time | No |
| Server variable, in prerendered code | At build time | No |
Server variable, after io() or request data |
On every request | Yes |
| Server variable, in a Server Action or a Route Handler responding to the request | When it runs | Yes |
Check it: build with SITE_NOTICE empty and start with SITE_NOTICE="Test" npm run start. The notice appears without rebuilding. If a Client Component needs a value like this, pass it as a prop from a component that has read it this way; it's the alternative to NEXT_PUBLIC_ when a single build goes to several environments. In module 6, the maximum spots per booking will reach the form in exactly this way.
- How a secret escapes
Let's bring the paths together. Almost all of them are silent.
| Leak | How it happens | Barrier |
|---|---|---|
| Wrong prefix | NEXT_PUBLIC_API_KEY "to make it work" |
Review the names; the secret doesn't leave the server |
| Import | A module with the key reaches the client | server-only |
| Prop | The configuration object or the full record is passed | Build minimal objects |
| Return value | A Server Action returns too much | Same (06-01) |
| Error message | The connection string is shown or logged | Your own messages; error.message isn't displayed (02-04) |
| Repository | .env.local is versioned |
.gitignore, and rotate the secret if it happens |
public/ folder |
A configuration file is left there | Everything in there is public (01-03) |
| Project details | Internal addresses in comments in client code | Treat everything the client imports as public |
The documentation also suggests concentrating secrets: only the data layer should touch process.env. In AgendaViva, lib/env.ts does it, and the data layer asks it.
React has an additional safeguard, the experimental_taintObjectReference and experimental_taintUniqueValue functions, which mark an object or a value so that passing it to the client throws an error. They're enabled with experimental.taint and, as their name says, they aren't recommended in production yet. They have important limits: a copy of the object or a derived value is no longer marked. They're a safety net underneath, not a substitute for sending only what's needed.
Common Mistakes and Tips
- Adding
NEXT_PUBLIC_to a secret because "it comes out empty on the client". It's empty for your own safety: move that call to the server. - Expecting a
NEXT_PUBLIC_to change on restart. Rebuild. - Destructuring
process.envto read a public variable on the client. It isn't replaced. - Comparing without converting.
process.env.ENABLEDwith the valuefalseis the string'false', which is truthy in a condition. - Reading a runtime variable in a prerendered component, without
io(). It keeps the build's value. - Putting
server-onlyin shared modules likelib/types.ts. It breaks the Client Components that legitimately use them. - Versioning
.env.local, or leaving real secrets in.env.example. - Validating the environment when the module is imported. It forces you to have the secrets on the machine that builds.
Exercises
Exercise 1: classifying variables
For each value, decide whether it gets NEXT_PUBLIC_, where it's defined and what happens if it changes in production: (1) the database address; (2) the ID of an analytics service loaded in the browser; (3) the key that signs sessions; (4) a switch to hide bookings during an incident; (5) the city's name.
Solution
- No prefix. On the production platform and in
.env.localin development. When it changes, you restart. - With the prefix. It isn't secret and the browser uses it. When it changes, you rebuild.
- No prefix, different in each environment. When it changes, open sessions are no longer valid.
- No prefix and read after
io(), or in the Server Action that books. It must be changeable without rebuilding; with the prefix it would be useless during an incident. - No variable at all. It doesn't change between environments: it's a constant in the code.
Exercise 2: a required variable
Add a readRequired(name) function to lib/env.ts that throws an error if the variable is missing or empty, and use it for a databaseUrl field read from DATABASE_URL. What would happen when building on a CI server that doesn't have it?
Solution
// lib/env.ts
function readRequired(name: string): string {
const value = process.env[name]?.trim()
if (!value) {
throw new Error(`Missing variable ${name}. See .env.example`)
}
return value
}
// In readEnv()
databaseUrl: readRequired('DATABASE_URL'),Since readEnv is a function, importing it doesn't check anything. The build would only fail if some code running during prerendering called it. In AgendaViva, SiteNotice calls it after io(), that is, during the request. It's an exercise: the field will be added to the project in 04-02.
Exercise 3: auditing a module
Find the problems in this code and fix it.
// lib/weather.ts
export async function getWeather(district: string) {
const key = process.env.NEXT_PUBLIC_WEATHER_KEY
const response = await fetch(
`https://weather.example.com/v1?district=${district}&key=${key}`,
)
return response.json()
}
// components/weather.tsx
'use client'
export function Weather({ district }: { district: string }) {
const data = use(getWeather(district))
return <p>{data.degrees} degrees</p>
}Solution
- The key is public, because of the prefix and because it travels in a request from the browser.
- The module isn't protected and a Client Component imports it.
usereceives a new promise on every render (03-03).districtis concatenated into the URL without encoding, and the full response is returned without checking whether there was an error.
// lib/data/weather.ts
import 'server-only'
export async function getDegrees(district: string): Promise<number | null> {
const url = new URL('https://weather.example.com/v1')
url.searchParams.set('district', district)
const response = await fetch(url, {
headers: { Authorization: `Bearer ${process.env.WEATHER_KEY}` },
})
if (!response.ok) return null
const data: { degrees?: number } = await response.json()
return data.degrees ?? null
}
// components/weather.tsx
import { getDegrees } from '@/lib/data/weather'
export async function Weather({ district }: { district: string }) {
const degrees = await getDegrees(district)
return degrees === null ? null : <p>{degrees} degrees</p>
}The component had no state or events, so it moves to the server. The key travels in a header, from server to server, and only a number reaches the browser. In the project, the key would be read with readEnv(). Whoever uses it must wrap it in a <Suspense>.
Conclusion
server-only and client-only turn an import slip into a build error. Environment variables live on the server, except the ones you publish with NEXT_PUBLIC_, which are fixed at build time; the rest are read when the code runs, and io() guarantees that happens during the request. A single module validates them, and instrumentation.ts does so at startup. None of these barriers replaces the underlying rule: whatever crosses the boundary is public.
That wraps up module 3. You know what runs where, what travels and what doesn't, and AgendaViva has its first interactive islands and a protected data layer. It's time to study that layer from the inside. Module 4 starts with Reading Data on the Server, where you'll see how Server Components read data beyond the in-memory array that has kept us company so far.
