🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Server-Side Rendering: Hydration, Streaming and SEO

React AdvancedđŸŸĸ Free Lesson

Server-side rendering exists because the first paint is the only one most visitors see. If the server sends an empty root element and a large script bundle, the browser must download, parse and execute that bundle before anything appears, and on a mid-range phone over a normal connection that gap is measured in seconds during which the reader sees a blank page. Rendering on the server turns the wait into markup delivery, so text and layout arrive with the first response while JavaScript wakes the page up afterwards.

â„šī¸Two phases, two failure modes

Server rendering decides what the first paint looks like. Hydration decides whether interactivity attaches at all. A defect in the first is a slow or blank page; a defect in the second is a console full of mismatch errors and, in the worst case, event handlers that silently do nothing.

What the server actually sends

The server runs your component tree, produces HTML, and ships it along with the data needed to rebuild the tree on the client. The browser paints that HTML immediately, which is what improves the largest contentful paint and makes the page readable before any script has executed. Then the framework downloads the component code, reconstructs the tree in memory, and walks the existing markup attaching listeners, a process called hydration. Only after it completes do buttons respond.

Everything that happens during hydration has to agree with what the server produced. React compares the expected tree with the DOM it finds, and any disagreement in text, structure or attributes is a mismatch. React will patch the difference and log a warning in development, but the warning is the symptom of a real class of bug: the two renders were not deterministic, and the next one may not be either.

Rendering a page on the server

In a framework with a server runtime the page component is async, receives its data directly, and returns the markup. The client component that needs interactivity is imported normally, and the framework ships its code separately.

import { notFound } from 'next/navigation';
import { Suspense } from 'react';
import { db } from '@/lib/db';
import AddToCart from './add-to-cart';
import Reviews from './reviews';

async function getProduct(slug) {
  const product = await db.product.findFirst({ where: { slug } });
  if (!product) notFound();
  return product;
}

export default async function ProductPage({ params }) {
  const product = await getProduct(params.slug);

  return (
    <main>
      <article>
        <h1>{product.name}</h1>
        <p className="price">${product.price.toFixed(2)}</p>
        <p>{product.summary}</p>
        <AddToCart productId={product.id} />
      </article>

      <Suspense fallback={<ReviewsSkeleton />}>
        <Reviews productId={product.id} />
      </Suspense>
    </main>
  );
}

export async function generateMetadata({ params }) {
  const product = await getProduct(params.slug);
  return {
    title: product.name,
    description: product.summary.slice(0, 155),
    openGraph: { images: [product.image] },
  };
}

Metadata generation is part of the same request, which matters for search engines and link previews: the title, description and social image are all present in the initial response rather than appended later by a script. Anything that needs data should be fetched before the response is committed, because content added after the fact never reaches a crawler that does not run JavaScript.

Hydration: where mismatch errors come from

Most mismatches come from code that is not deterministic between the two environments rather than from a framework defect. Reading the clock or a random number during render produces different text on the server and the client. A branch on window.innerWidth takes one path on the server, where it does not exist, and another in the browser. An effect that changes content does not run on the server at all, so the first client render must still match the server output before the effect fires.

import { useEffect, useState } from 'react';

function formatTimestamp(iso) {
  const date = new Date(iso);
  return new Intl.DateTimeFormat('en-GB', {
    day: '2-digit', month: 'short', year: 'numeric',
  }).format(date);
}

export function PublishedAt({ iso }) {
  const [mounted, setMounted] = useState(false);
  useEffect(() => setMounted(true), []);

  if (!mounted) {
    return <time dateTime={iso}>{formatTimestamp(iso)}</time>;
  }

  const relative = formatRelative(iso);
  return <time dateTime={iso} title={formatTimestamp(iso)}>{relative}</time>;
}

The mounted guard works because the server output and the first client render are identical, and only after hydration does the component switch to the browser-only presentation. Use the same technique for anything locale-dependent: format the timestamp for a neutral locale during server rendering, then refine it to the reader's locale after mount. Suppressing the warning instead of fixing the divergence hides the problem and ships a page where the two environments genuinely disagree.

Streaming the shell first, then the slow regions

Time to first byte is bounded by whatever the server must finish before writing the response. Streaming breaks that dependency: the document head, navigation and placeholders flush immediately, and each Suspense boundary writes its real markup when its data resolves, followed by a small inline script that swaps the placeholder. The reader sees structure at once and content as it arrives.

The discipline is that every fallback must be the size and shape of what it replaces. A one-line skeleton above a table that is eight hundred pixels tall produces a burst of layout shift when the data lands, which directly penalizes the cumulative layout shift metric. Reserve the space, announce the loading region with a status role, and the swap becomes visually silent.

Choosing between rendering modes

The right mode is a property of the data, not of the framework.

ModeBuiltFreshnessBest forCost
Static generationAt build timeStale until rebuildDocumentation, marketing, fixed contentCheapest to serve, slowest to update
Incremental regenerationOn demand per pathMinutes of stalenessCatalogues and articles with traffic patternsCache invalidation logic to maintain
Server-side renderingPer requestAlways currentPersonalized or frequently changing pagesServer cost per hit, needs caching in front
Client-side renderingIn the browserAlways current after loadHeavier applications behind loginLongest time to first content
Streaming server renderingShell first, then partsCurrentPages mixing fast and slow dataRequires boundaries and sized fallbacks

A practical sequence for a growing product is static pages for everything that does not change, server rendering for the pages that carry live inventory or user data, and client rendering only inside authenticated application areas where a cache would be dangerous anyway.

Measuring and fixing time to first byte

The chain that decides perceived speed is server response time, then download, then render, then hydration. Instrument each link. A slow server response usually means an uncached database query running inside the render path, so move it behind a cache or compute it before the render starts. A large document suggests unbounded queries returning enormous payloads to the client. A slow hydration points at expensive components mounted in the initial tree, which is where boundaries and lazy loading pay off even on a server-rendered page.

Report the metrics from real sessions rather than from your own machine, because the field numbers are the ones search engines and users experience. A page that scores well in a lab on a fast connection and takes four seconds on a mid-range phone has not been optimized; it has been measured in the wrong place.

Common Mistakes

Rendering clock, random or locale-dependent values directly during render

Fix: Produce identical output on both passes and refine the value in an effect after hydration.

Letting the server wait for every query before sending the first byte

Fix: Send the shell immediately and stream slow regions behind Suspense boundaries with sized fallbacks.

Relying on client-side effects to populate titles, descriptions and social images

Fix: Generate metadata during the server render so crawlers and link previews receive it in the initial response.

Choosing the rendering mode because it is the default in the framework

Fix: Decide from how fresh the data must be and who is allowed to see it, then pick the mode that matches.

Key Takeaways

  • Server rendering improves the first paint; hydration is what makes the page interactive, and the two must agree exactly
  • Mismatch errors almost always come from non-deterministic code, so fix the divergence instead of silencing the warning
  • Streaming sends the shell first and fills slow sections later, which lowers time to first byte without hiding content
  • Metadata must be produced on the server or crawlers and link previews never see it
  • Match the mode to the data: static for fixed content, server rendering for live data, client rendering behind login
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert React Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement