Part 05 / Topic 4 of 6
Keeping secrets on the server: server-only
Nothing has stopped a plain TypeScript module like wholesale.ts from being imported anywhere else in the project yet — including, by accident, into a Client Component file, which would try to ship its code (and the real SUPPLIER_HELPLINE string inside it) to every visitor's browser. The server-only package (installed in this harness with npm install server-only, confirmed present at node_modules/server-only) closes that door for good: a module that starts with import "server-only"; throws a build error, not a runtime leak, the moment anything tries to pull it into a Client Component.
Reproduced for real against the actual wholesale.ts module above, by adding a scratch Client Component that imports SUPPLIER_HELPLINE from it:
"use client";
import { SUPPLIER_HELPLINE } from "../../lib/wholesale";
export default function LeakTest() {
return <p>{SUPPLIER_HELPLINE}</p>;
}
$ npm run build
...
Error: Turbopack build failed with 2 errors:
./app/store/lib/wholesale.ts:7:1
Error: You're importing a module that depends on "server-only" into a React Client Component module. This API is only available in Server Components but one of its parents is marked with "use client", so this module is also a Client Component.
Learn more: https://nextjs.org/docs/app/building-your-application/rendering
...
./app/store/lib/wholesale.ts:7:1
Error: 'server-only' cannot be imported from a Client Component module
...
It should only be used from a Server Component.
Two separate errors fire for the same mistake — Next.js's own React Server Components plugin catches it once, and the server-only package's own thrown Error (its entire implementation is one throw new Error(...) statement, readable directly in node_modules/server-only/index.js) catches it a second time, as a safety net in case anything ever bypasses the first check. Both scratch files used for this reproduction were deleted immediately after, the same as section 3.
The companion package, client-only, does the identical job in the opposite direction (guarding a browser-only module, like one that touches localStorage, from ever being imported into a Server Component) and was already present in this harness's node_modules as a transitive dependency before this part added anything — confirmed by listing it directly, not assumed.
A second, equally real way the same secret could leak is simply not having a server-only guard and trusting yourself to never write the bad import. server-only turns that trust into a build failure instead. The environment-variable half of "keeping secrets on the server" — NEXT_PUBLIC_-prefixed variables are the only ones a browser ever sees, every other variable stays server-side automatically — is the same idea applied to configuration rather than code, and is Stage 4's territory once a real .env file enters the course.
Done here? The practice set for Part 5 — including the solutions — is on the part page.