Keeping server code on the server
Secrets leak when server code accidentally gets imported into a Client Component. React ships two marker packages that turn that mistake into a build-time error:
// lib/db.ts
import 'server-only';
export async function getUsers() {
return db.query('select * from users');
}
Importing server-only at the top of a module guarantees the module may only be
used by Server Components. If a Client Component imports it — directly or through
a chain — the build fails with a clear message instead of silently bundling your
database client and credentials into the browser.
client-only is the mirror image: it marks a module that must never be imported
into a Server Component, for code that depends on the browser.
Neither package ships any runtime behaviour. They are markers: the enforcement is the build error you get in the wrong environment, and that is the point — a mistake surfaces at build time rather than in production.
The usual place to apply server-only is a data access layer that holds API
keys, database connections, and authorization logic, so those never travel to the
client.
You are about to answer a short quiz on server-only / client-only.