The 'server-only' package is a tool that ensures certain modules or functions can ONLY be imported and executed on the server.
Interactive Concept Walkthrough
Zero-Leak Simulation
Enforcing Server-Only Boundaries
DB_PASSWORD"********"
'server-only' active
Client Bundle
Publicly viewable
Safe by Default: By using the server-only package, you ensure that internal logic or sensitive keys can neverbe accidentally imported into a Client Component.
Editable Code Example
page.tsx
Editable Code Example1// lib/secrets.ts
2import 'server-only'
3
4export const API_KEY = process.env.SECRET_KEY
5
6// If you import this in a Client Component,
7// Next.js will throw a build error!Mental Model
A VIP security guard. If any part of your app tries to take 'secret' code to the browser, the guard stops it immediately.
Why This Exists
To prevent sensitive information like API keys or database credentials from accidentally being sent to the user's browser.
Critical Note
"Developers often confuse this pattern with traditional client React. Use the editable code example above to follow the walkthrough."