Q23: How does the server-only package safeguard private backend utility code?
Importing import 'server-only' into utility files guarantees that private code (API tokens, database credentials) is never accidentally imported into Client Components. If a Client Component imports a server-only file, Next.js throws a build-time error.
Enforcing Server-Only Boundary
// lib/db-queries.js
import 'server-only'; // Guarantees this file cannot be bundled for client
export async function getSensitiveData() {
return db.query('SELECT * FROM secret_table');
}Importing server-only breaks builds instantly if client code attempts to import db-queries.js.
Key Takeaways
Protects sensitive server logic from leaking into client JavaScript bundles.
Throws explicit compilation errors during build time if boundary leaks occur.
Knowledge Check
What occurs during build time if a Client Component ('use client') imports a module containing import 'server-only'?