My account

SSR and Server Components

Server rendering sends real HTML, so the user sees the page before the JavaScript arrives. Hydration then attaches React to that HTML, and it breaks if the server and the browser render different things. React Server Components go one step further - they run only on the server and send no JavaScript at all. A specialist must know where the line between server and client is, what can cross it, and that every server function is a public endpoint.

Not reviewedWritten with AI helpReading time: 18 minOnline shop exampleReact 19Next.js App Router

Author: bezzad

Contents

The problem: an empty page on a slow phone

Our product page is a client-rendered app. The server sends an almost empty HTML file with one <div id="root"> and a big JavaScript file. Then:

  1. On a slow phone, the user sees a white page for 4 seconds. The browser must download, parse and run all the JavaScript, then fetch the product, and only then draw it.
  2. Search engines and link previews see an empty page with no product name or price.
  3. The page ships a Markdown parser of 80 KB only to show the product description once.

Rendering on the server fixes the first two. Server Components fix the third.

Client rendering, server rendering and static pages

CSRHTMLdownload + run JavaScriptfetch datashows + worksUntil here: a white pageSSRserver renderscontent visibleHydrationshows + worksThe user sees the product earlytime →
With client rendering, nothing useful shows until the JavaScript runs and the data comes. With server rendering, the HTML already has the content, so the user sees it early. The page becomes interactive after hydration.
  1. Client-side rendering (CSR): the browser builds the whole page. Simple hosting, but a slow first view and weak for SEO.
  2. Server-side rendering (SSR): for each request, the server runs the components and sends full HTML. The user sees content early. The same components then run again in the browser to make the page interactive.
  3. Static site generation (SSG): the HTML is made once, at build time. Very fast and cheap. Good for pages that are the same for everyone, like a blog post or a help page.
  4. Many apps mix them: static marketing pages, SSR product pages, and client-only parts like the admin dashboard.

Hydration and hydration errors

In SSR, the browser first shows the server’s HTML. Then React runs the components again in the browser and attaches event handlers to the existing HTML, without rebuilding it. This step is hydration.

For hydration to work, the first render in the browser must give exactly the same HTML as the server. If not, React shows a hydration error, and it may throw away the server HTML and render again on the client, which is slow and can flash.

// Bad: different on the server and in the browser
function SaleBadge({ endsAt }: { endsAt: number }) {
  const minutes = Math.round((endsAt - Date.now()) / 60_000);
  return <span>Sale ends in {minutes} min</span>;
}

Common causes of a mismatch:

  1. Time and random values: Date.now(), new Date().toLocaleString(), Math.random().
  2. Browser-only values: window, localStorage, the screen width, the user’s time zone and language.
  3. Invalid HTML: for example a <div> inside a <p>. The browser fixes the HTML, so it no longer matches.

The fix: render a stable value first, then update after hydration.

import { useEffect, useState } from 'react';

function SaleBadge({ endsAt }: { endsAt: number }) {
  const [now, setNow] = useState<number | null>(null);

  useEffect(() => {
    setNow(Date.now());
    const id = setInterval(() => setNow(Date.now()), 60_000);
    return () => clearInterval(id);
  }, []);

  if (now === null) return <span>Sale ends soon</span>;
  return <span>Sale ends in {Math.round((endsAt - now) / 60_000)} min</span>;
}

The server and the first browser render both show “Sale ends soon”. The effect runs only in the browser, after hydration.

Streaming with Suspense

A server render waits for its slowest data. With streaming, React sends the HTML in parts:

  1. The server sends the page shell and the product details at once.
  2. The reviews are slow, so they are inside a Suspense boundary. The server sends the fallback first, then the reviews HTML later on the same response, when they are ready.
  3. Each part can also hydrate on its own. React hydrates the part the user clicks first.

So one slow API no longer blocks the whole page.

Server Components: code that never goes to the browser

ProductPageserver, reads the databaseDescriptionserver, uses markedReviewsserver, asyncAddToCart'use client'{ productId, price }Server componentdata, secrets, big libraries0 KB JavaScript in the browserClient componentstate, effects, onClickits code goes to the browser
Server components run only on the server and send no JavaScript. Client components are the interactive parts. Only serializable props can cross from server to client.

In a framework that supports them (for example the Next.js App Router), components are Server Components by default:

// ProductPage.tsx: a Server Component
import { marked } from 'marked';
import { db } from './db';
import { AddToCart } from './AddToCart';

export default async function ProductPage({ id }: { id: string }) {
  const product = await db.product.find(id); // direct database access
  const html = marked.parse(product.description);
  return (
    <article>
      <h1>{product.name}</h1>
      <div dangerouslySetInnerHTML={{ __html: html }} />
      <AddToCart productId={product.id} price={product.price} />
    </article>
  );
}
// AddToCart.tsx: a Client Component
'use client';
import { useState } from 'react';

export function AddToCart({ productId, price }: { productId: string; price: number }) {
  const [count, setCount] = useState(1);
  // ... buttons with onClick
}
  1. A server component can be async, can read the database or secret keys directly, and its code (and the Markdown parser) is not sent to the browser. It cannot use state, effects or event handlers.
  2. ‘use client’ marks a file as the border. That component and everything it imports go to the browser, are rendered on the server for the first HTML, and are then hydrated.
  3. Only serializable props cross the border: strings, numbers, plain objects, arrays, dates, promises and JSX. A normal function or a class instance cannot be passed to a client component.
  4. Keep ‘use client’ low in the tree. Make the small interactive leaf a client component, not the whole page.
  5. Composition still works: a client component can get server components as children.

Note: the Markdown in this example comes from our own admin. If it can come from users, sanitize the HTML first.

Server Functions are public endpoints

'use server';
import { auth } from './auth';
import { db } from './db';
import { z } from 'zod';

const Input = z.object({ productId: z.string(), price: z.number().positive() });

export async function updatePrice(raw: unknown) {
  const user = await auth();
  if (!user?.isAdmin) throw new Error('Forbidden');
  const { productId, price } = Input.parse(raw);
  await db.product.update(productId, { price });
}

A function in a ‘use server’ file can be called from the browser like a normal function. The framework turns it into an HTTP endpoint. Anyone can call that endpoint with any data, not only your form. So:

  1. Check the user’s rights inside the function, every time.
  2. Validate the input. TypeScript types do not exist at run time.
  3. Treat it like any other API: rate limits, logs, and no secret data in the response.

When not to use it

Server rendering adds a server to run, more complex caching, and new kinds of bugs. A dashboard behind a login, with no SEO need, is often fine as a client app. Measure the first view (LCP) and the interaction speed (INP) before and after, on a real slow phone.

Common mistakes

Mistake Result Better way
Date.now() or window in the first render Hydration error and a flash. Stable first render, then update in an effect.
‘use client’ at the top of the page The whole page goes to the browser again. Make only the interactive leaves client components.
Passing a function prop from server to client Error: it cannot be serialized. A server function, or move the logic to the client component.
No auth check in a server function Anyone can call it with any data. Check rights and validate input inside it.
One slow API blocks the server render A late first view. Streaming with Suspense around the slow part.
SSR for every page Server cost and complexity with no gain. Pick CSR, SSR or static per page.

Summary in 6 lines

  1. CSR builds the page in the browser, SSR builds HTML per request, SSG builds it at build time. Mix them per page.
  2. Hydration attaches React to the server HTML. The first browser render must match the server exactly.
  3. Streaming with Suspense sends the fast parts first, and each part hydrates on its own.
  4. Server components run only on the server, can read data directly, and send no JavaScript.
  5. ‘use client’ marks the border. Keep it low, and pass only serializable props across it.
  6. Every server function is a public endpoint. Check rights and validate input inside it.

Done reading this lesson?Mark it as finished so it shows in your lessons list and report card.