Course map
Stage 1: App Router Foundations
Stage 2: The Rendering Model
Stage 3: Data, Caching and Mutations
Stage 4: Full-Stack Next.js
Stage 5: Production and Specialization

Part 17 / Topic 2 of 8

Gotcha #1: server-only throws on import under a plain Vitest config

Every QuickCart data-access file starts with import "server-only" (Part 16's convention). The very first attempt at testing one of them hit this immediately:

$ npm run test
 FAIL  app/quickcart/lib/products.test.ts [ app/quickcart/lib/products.test.ts ]
Error: This module cannot be imported from a Client Component module. It should only be used from a Server Component.
 ❯ Object.<anonymous> node_modules/server-only/index.js:1:7

The installed server-only package's own package.json explains exactly why, in its exports map:

"exports": { ".": { "react-server": "./empty.js", "default": "./index.js" } }

Next's own bundler sets the "react-server" module resolution condition when it builds the real app, so server-only resolves to a silent no-op (empty.js) there. Vite/Vitest run in plain Node with no reason to set that condition, so every import resolves to index.js — which just throws, by design, to stop a client bundle from ever shipping server-only code. Fix: alias server-only straight to its own empty.js inside vitest.config.mts (examples/01-vitest-config.mts, section "resolve.alias"). After the alias, the exact same test file imports cleanly and the throw is gone — confirmed by re-running npm run test with the alias in place (section 4's output).

Done here? The practice set for Part 17 — including the solutions — is on the part page.

Search the guide