Next.js Course
Next.js
/
Intermediate

Server vs Client Components

Definition

The architectural decision-making process of choosing exactly when to leave a component on the server, and when to opt-in to the client.

Explain Like I'm New

The golden rule of modern Next.js: Keep EVERYTHING as a Server Component by default. Only extract the tiny, interactive pieces (like a button or an input field) into Client Components.

Real World Example

You have a massive Blog Post page. The Header, the Article Text, and the Footer should all be Server Components. The tiny 'Like Button' at the bottom should be extracted into its own file, marked with `'use client'`, and imported into the Server Component.

Common Use Cases

  • Optimizing application performance
  • Architecting Next.js layouts

Interactive Example

/* ❌ BAD ARCHITECTURE (Whole page is a Client Component) */
'use client'; // This forces the massive article text to be sent as JS to the browser!
import { useState } from 'react';
export default function BlogPost({ article }) {
  const [likes, setLikes] = useState(0);
  return (
    <article>
      <h1>{article.title}</h1>
      <p>{article.massiveContent}</p>
      <button onClick={() => setLikes(l=>l+1)}>Like {likes}</button>
    </article>
  );
}

/* ✅ GOOD ARCHITECTURE (Push interactivity down the tree) */
// app/blog/page.tsx (Server Component)
import LikeButton from './LikeButton'; // Import the tiny interactive part
export default function BlogPost({ article }) {
  return (
    <article>
      {/* This massive text stays on the server, never sent as JS! */}
      <h1>{article.title}</h1>
      <p>{article.massiveContent}</p>
      {/* Only this tiny button gets sent to the browser */}
      <LikeButton />
    </article>
  );
}

Interview Questions

basic

  • If you need to fetch secret API keys from the environment variables, should you use a Server or Client component?

intermediate

  • What happens if you try to use `window.innerWidth` inside a Server Component?

Flash Cards

Question

Server or Client for secrets?

Click to reveal answer
Answer

Server Component! Client components are sent to the browser, meaning users can inspect the code and steal your API keys. Server components stay safely on the server.

Question

window in Server Component?

Click to reveal answer
Answer

It will throw an error: `window is not defined`. The `window` object only exists in web browsers. Server Components run in Node.js, which has no concept of a browser window.