Protecting Server-Only Modules
A large application can accidentally import server-only functionality into client code. This can expose secrets or create build errors.
The server-only package can be used to explicitly mark modules that must never be imported into client code.
This is particularly useful for database clients, authentication utilities, payment providers, and internal service clients.
Think in Boundaries
The important question is not simply 'does this component render?' but 'where should this code execute?'
Server-Only Service
import 'server-only';
export async function getPrivateUserData(userId: string) {
// Database access or private API access
return database.users.findById(userId);
}💡 Marking the module as server-only creates an explicit architectural boundary.
Key Takeaways
- Use explicit server-only boundaries for sensitive modules.
- Database clients should never become browser dependencies.
- Server/client boundaries are architectural decisions, not just syntax.