Nextjs Fundamentals · Server & Client Components

Keeping server code on the server

`server-only` / `client-only`

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.

  1. Importing `server-only` in a module makes the build fail if a Client Component imports that module.
  2. Import ___ in a module to guarantee it is only used in server code.
  3. `client-only` marks a module that must not be imported into a Server Component.
  4. `server-only` and `client-only` are marker packages whose enforcement is a build-time error.
  5. A common place to apply `server-only` is a ___ that holds API keys or database access.