Next.js
/Advanced
Server Component Patterns
Definition
Advanced architectural techniques for mixing Server and Client components safely, effectively managing state, and avoiding common pitfalls like 'Poisoning' the client bundle.
Explain Like I'm New
Mastering Next.js is knowing exactly where to draw the line between Server and Client. Bad patterns result in passing 50 props between files or accidentally leaking secure database code to the browser. Good patterns use composition, context, and strict boundaries.
Real World Example
Using the `server-only` package. If you have a helper function `verifyPassword()`, you import `'server-only'` at the top of the file. If a developer accidentally imports that function into a Client Component, the build will violently crash, preventing a massive security leak.
Common Use Cases
- •Codebase security
- •Architecture design
- •Performance tuning
Interactive Example
// lib/db-helpers.ts // 1. This prevents this file from ever entering the browser bundle! import 'server-only'; export async function getSecureAdminData() { return db.query('SELECT * FROM admin_secrets'); } // ----------------------------------------------------- // app/page.tsx (Server Component) import ClientInteractiveChart from './ClientChart'; export default async function Page() { const data = await getSecureAdminData(); // 2. Data serialization rule: // You CANNOT pass the raw DB response if it contains complex Objects (like Dates). // You must map it down to pure serializable JSON strings/numbers first! const safeData = data.map(row => ({ id: row.id, dateStr: row.createdAt.toISOString() // Convert Date object to String! })); return <ClientInteractiveChart data={safeData} />; }
Interview Questions
basic
- What happens if you pass a complex JavaScript Class (like a `Date` object) as a prop from a Server Component to a Client Component?
intermediate
- What is the 'server-only' package used for?