The Web FrontendVol. 2 · Part II
0 / 0

Shelves / The Web Frontend

FE·24

Full-stack Frameworks

Rendering strategies (CSR, SSR, SSG, ISR, streaming, partial rendering, islands, server components, edge) and the frameworks that implement them: Next.js, React Router, Astro, SvelteKit and Nuxt, with Next.js production concepts in depth.

41 topics · ~28 min read · 27-question quiz
Updated Suggest a correction

Start here: where pages get built

The question every web app has to answer

Before a user can see a page, someone has to turn data (today's menu, from a database) and components (chapter 22) into HTML. The only question is where and when:

Strategy Where the HTML is made When Tiffin-service analogy
CSR (client-side rendering) in the user's browser, by JavaScript after the JS downloads and fetches data delivering ingredients and a recipe; the customer cooks
SSR (server-side rendering) on the server on every request cooking each order fresh in the kitchen, then delivering
SSG (static site generation) on a build machine once, when the site is built lunchboxes packed at 6 am, handed out instantly
ISR (incremental static regeneration) on the server at build, then again every so often packed lunchboxes, with a fresh batch made every hour
Streaming SSR on the server per request, sent in pieces serving the starter immediately while the curry finishes
Islands static HTML from the server, plus small interactive pieces mostly at build a printed menu with one live order button

Most real sites mix them: a marketing page is static, a product page is regenerated hourly, a dashboard renders per user, and an editor runs in the browser. Full-stack frameworks (Next.js, React Router, Nuxt, SvelteKit, Astro, Angular's SSR; chapter's full-depth sections) exist to let you choose a strategy per page without building the plumbing yourself.

CSR: the browser does everything

A plain React app (chapter 22) is CSR. The server sends an almost empty page:

HTML
<div id="root"></div><script type="module" src="/csr.js"></script>

The browser downloads the JavaScript (224 KB here: React plus the app), runs it, the app fetches /api/dishes, and only then renders the menu. Until all three steps finish, the user stares at a blank page, and search engines and link previews see nothing.

SSR: the server sends finished HTML

With SSR, the server fetches the data and runs the same components on the server to produce HTML. React's renderToString turned the menu component into:

HTML
<main><h1>Today&#x27;s menu</h1><ul><li>Masala dosa<!-- --> ₹<!-- -->90<!-- --> <button>Add</button></li>…</ul>
<p id="cart">Cart: <!-- -->0<!-- --> item(s)</p></main>

The user sees the menu as soon as that HTML arrives. But it's just HTML: the Add buttons don't work yet. The page also includes the data the server used and the same JavaScript as before, and when it loads, React hydrates: it runs the components again in the browser, checks they produce the same structure, and attaches event handlers to the existing elements instead of re-creating them:

JSX
const dishes = JSON.parse(document.getElementById("data").textContent);   // the data the server used
hydrateRoot(document.getElementById("root"), <Menu dishes={dishes} />);   // attach to the existing HTML

(The <!-- --> comments mark where separate text pieces join, so hydration can match them up.)

SSG: build it once, serve it instantly

If the menu changes once a day, why render it on every request? SSG runs the same server rendering once, at build time, writes HTML files, and serves them from a CDN (chapter 31) like any static file. The page is as fast as a hand-written HTML file. The catch is freshness: the page shows the data as it was at build time, until you rebuild. ISR and on-demand revalidation close the gap by re-rendering a page in the background after a time limit or when the data changes.

The three, measured

The same menu page served three ways, five runs each (median), on the throttled phone profile:

Text
CSR  first byte    5 ms | menu visible  1693 ms | Add button works  1727 ms
SSR  first byte  306 ms | menu visible   401 ms | Add button works  1687 ms
SSG  first byte    4 ms | menu visible   103 ms | Add button works  1381 ms
  • CSR answered instantly but showed nothing for 1.7 seconds: download the JavaScript, run it, fetch the data, render.
  • SSR made the user wait 300 ms for the first byte (the server was querying the database), but showed the menu at 0.4 s, four times sooner.
  • SSG had no server work at all: the menu appeared in 0.1 s.
  • But look at the last column: in every strategy the button only worked after the same 224 KB of JavaScript had downloaded and run. SSR and SSG make pages visible sooner, not interactive sooner. The gap between "I can see the button" and "the button works" is a real usability problem on slow phones, and reducing the JavaScript that must load before interaction is what streaming, islands and Server Components (full-depth sections) are about.

Streaming: send what's ready, then the rest

A product page has fast data (name, price) and slow data (reviews from another service). Plain SSR waits for the slowest query before sending anything. Streaming SSR sends the page in pieces. With React's renderToPipeableStream and a <Suspense> boundary around the reviews, the server's response arrived as two chunks:

Text
+  34 ms  chunk of  270 bytes: <!DOCTYPE html><html><head></head><body><main><h1>Masala dosa</h1><p>₹90 · crisp, with potato masala</p>
                               <!--$?--><template id="B:0"></template><p>Loading reviews…</p>…
+ 825 ms  chunk of  966 bytes: <div hidden id="S:0"><ul><li>Best in Hyderabad</li><li>Chutney was perfect</li></ul></div><script>…</script></body></html>

The browser showed the name, price and a "Loading reviews…" placeholder after 34 ms. When the slow service answered 800 ms later, the server sent the reviews' HTML plus a tiny inline script that swaps it into the placeholder's position, all in the same HTTP response, no extra request.

Hydration has to match

Hydration assumes the browser renders exactly what the server rendered. When it doesn't, React complains and throws the server's HTML away:

JSX
function Clock() { return <p>Rendered at {new Date().toLocaleTimeString("en-IN")}</p>; }      // different on each machine
function Greeting() { return <p>{typeof window === "undefined" ? "Hello, guest" : "Hello, Asha"}</p>; }
Text
Hydration failed because the server rendered text didn't match the client. As a result this tree will be
regenerated on the client. This can happen if a SSR-ed Client Component used…

The page still worked, but React re-rendered the whole tree in the browser, losing SSR's benefit and possibly flashing. Typical causes: dates and times, random numbers or ids, window/localStorage checks during render, browser extensions that edit the DOM, and invalid HTML nesting. Render such values after hydration (in an effect), pass them from the server, or use useId for ids.

How deep to go in full-stack frameworks

Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.

Level What you can do
L1 Explain CSR, SSR, SSG, ISR, streaming, islands and hydration
L2 Build a framework app with routes, layouts, data loading, mutations and the right strategy per page
L3 Explain hydration and its costs, Server Components and the client boundary, caching layers, edge vs Node runtimes
L4 Diagnose hydration mismatches, waterfalls, stale caches, slow TTFB and oversized client bundles
L5 Choose a framework and rendering architecture for a product; design caching and revalidation
L6 Operate it: deployment targets, cache invalidation at scale, framework upgrades, cost per request

Rendering strategies

Where and when HTML is made

The defining decision of a web architecture is where (browser, server, edge, build machine) and when (build time, request time, interaction time) the HTML is produced. Each strategy trades time to first byte, time to content, interactivity, freshness, cost and complexity:

build timerequest timein the browser SSGstatic HTML on CDN ISRstatic + revalidate SSRper request Streaming SSRprogressive Edge renderingnear the user CSR / SPAJS builds the DOM Hydrationattach interactivity Islands · Server Components · Partial prerendering = server HTML + small client parts WHEREserver /CDN / edgebrowser →
Rendering strategies on two axes: when HTML is produced and where. Modern frameworks mix them per route.

CSR: client-side rendering

The server sends a nearly empty HTML shell plus a JavaScript bundle. The browser downloads and runs it, fetches data, and builds the DOM. This is the classic SPA (Create React App style, or Vite + React or Angular without SSR).

  • Pros: simple hosting (static files on a CDN), rich app-like interactivity, a clear API boundary (the frontend talks to a REST or GraphQL backend), and cheap servers.
  • Cons: slow first content (HTML → JS download → parse → execute → fetch data → render, a waterfall), a blank page until JS runs, weaker SEO and link previews (crawlers vary in how well they run JS), the entire app's JS shipped up front unless code-split, and poor performance on low-end phones.
  • Good for: authenticated dashboards, internal tools and admin panels, apps behind a login where SEO doesn't matter and users return often (caches warm).

SSR: server-side rendering

On each request, the server runs the components, fetches data, and sends complete HTML. The browser shows content immediately, then downloads JS and hydrates (chapter 22).

  • Pros: fast first content (good LCP), content in the HTML (SEO, link previews), works before JS loads, and data fetched close to the database.
  • Cons: a server is needed per request (cost, scaling, cold starts); TTFB includes server data fetching, so slow queries delay everything unless you stream; the hydration cost remains, so the page is visible before it's interactive; and code must be isomorphic, with server/client differences causing mismatches.
  • Good for: personalised pages that need fresh data and fast first paint: e-commerce product and cart pages, news, social feeds.

SSG: static site generation

Pages are rendered to HTML at build time and served from a CDN.

  • Pros: the fastest possible delivery (static files cached at the edge), the cheapest hosting, the smallest attack surface, and excellent reliability.
  • Cons: content is as fresh as the last build; build time grows with page count (100,000 product pages); and per-user personalisation needs client-side fetching or edge logic.
  • Good for: documentation, blogs, marketing sites, landing pages, and product catalogues that change infrequently.

ISR and revalidation

Incremental static regeneration combines SSG's speed with periodic freshness. Pages are generated statically (at build time or on first request), cached, and regenerated in the background when stale. That's stale-while-revalidate (chapter 19) applied to whole pages:

  • Time-based: "regenerate at most every 60 seconds". The first request after expiry gets the stale page and triggers a background rebuild, and later requests get the new page.
  • On-demand: regenerate when content actually changes. A CMS webhook or an admin action calls revalidatePath('/products/42') or revalidateTag('product-42').

Most CDN-backed frameworks implement this idea in some form: Next.js caching, Nuxt route rules (isr/swr), SvelteKit's isr config on Vercel, and Astro's adapters.

Streaming

Streaming SSR (chapter 22) sends HTML in chunks as it's ready. The shell and navigation go immediately, and slow sections arrive later, each replacing its loading fallback. That gives a fast TTFB and first paint even when some data is slow. It needs Suspense boundaries (React), {#await} (Svelte) or the equivalent, plus a host and CDN path that doesn't buffer responses. Watch for status codes and headers: once streaming starts, the HTTP status is already sent (200), so later errors must be shown in the page or handled by a redirect script.

Partial rendering and partial prerendering

Partial prerendering (PPR) (Next.js, maturing through 2025–2026) serves a static shell from the CDN instantly, with holes for dynamic parts, and streams the dynamic parts (cart count, personalised recommendations) from the server in the same response. Static and dynamic content mix within one page, at the component level, instead of per route. More generally, partial rendering means rendering only part of the page on navigation: nested layouts persist, and only the changed segment re-renders and streams. Every modern framework's nested routing does this.

Islands architecture

Islands (coined by Katie Sylor-Miller, popularised by Jason Miller and Astro): the page is static HTML by default, with small, independent interactive components (islands) that hydrate separately. A product page might have a static description and reviews, with a few islands: an image carousel, an add-to-cart button, a size picker.

astro
---
// Astro component: runs at build or request time; ships NO JS by default
import Gallery from "../components/Gallery.tsx";
import AddToCart from "../components/AddToCart.svelte";   // islands can mix frameworks
const product = await getProduct(Astro.params.slug);
---
<h1>{product.name}</h1>
<p>{product.description}</p>                              <!-- static HTML -->
<Gallery images={product.images} client:visible />         <!-- hydrates when scrolled into view -->
<AddToCart id={product.id} client:load />                  <!-- hydrates immediately -->
<Reviews productId={product.id} server:defer />            <!-- server island: rendered later on the server -->

Hydration directives (Astro): client:load, client:idle, client:visible, client:media, client:only. Islands minimise JavaScript, and therefore the INP and TBT cost, for content-heavy sites. Resumability (Qwik) goes further: instead of re-executing components to hydrate, it serialises the application state and listeners into the HTML and loads code only for the event the user actually triggers.

Server Components as a rendering strategy

React Server Components (chapter 22) generalise islands inside a React tree. Server components render to a serialised tree, and client components are the islands, but the framework handles navigation: subsequent navigations fetch an RSC payload for the new route segment and reconcile it into the existing page, keeping client state. RSC combines with SSR (the first load gets HTML) and streaming. Next.js App Router, React Router (RSC support arriving), Waku and RedwoodSDK implement it.

Edge rendering

Edge runtimes (Cloudflare Workers, Vercel Edge Functions, Deno Deploy, Netlify Edge, Fastly Compute) run JavaScript (V8 isolates, or Wasm) in hundreds of locations near users, with cold starts measured in milliseconds.

  • Good uses: low-latency personalisation and A/B tests (rewrite the static page per user), redirects, geolocation and i18n routing, authentication checks, header manipulation, and caching logic.
  • Caveats: the database is usually far from the edge. Rendering at the edge but querying a database in one region adds more latency (several round trips across the world) than rendering in the database's region. Edge runtimes also have a restricted API (Web APIs, not full Node), CPU-time limits, and smaller bundles. Common pattern: edge for routing and personalisation, regional servers next to the database for data-heavy rendering, or globally replicated data stores (Vol. 5).

Choosing a strategy

Page type Strategy
Docs, blog, marketing SSG (+ islands)
Large catalogue, changes hourly ISR / on-demand revalidation, or SSG + client fetch for prices and stock
Product page with personalised parts PPR / static shell + streamed dynamic parts, or SSR with caching
Logged-in dashboard CSR, or SSR + client components; SEO irrelevant
Search results, highly dynamic SSR + streaming
Global personalisation (geo, A/B) Edge middleware on top of static or ISR pages

Modern frameworks let you choose per route, and even per component, which is the main reason to use one instead of a bare SPA.

Frameworks

Next.js

Next.js (Vercel) is the most widely used React framework. It has two routers: the legacy Pages Router and the App Router (since v13, the default), which is built on React Server Components. It covers file-system routing, SSR/SSG/ISR/PPR, Server Functions, image, font and script optimisation, middleware and route handlers, with Turbopack as its bundler (the default for dev and build in recent versions). It's deployable on Vercel, on Node servers (next start, or output: "standalone" in Docker), or statically (output: "export", with SSR features lost). The OpenNext project helps self-host it on AWS, Cloudflare and Netlify.

React Router (framework mode)

React Router v7 merged with Remix. It can be used as a plain client router (library mode), or as a full framework (framework mode) with Vite, file- or config-based routes, and loaders and actions per route:

TSX
// app/routes/orders.$id.tsx
import type { Route } from "./+types/orders.$id";      // generated types per route

export async function loader({ params, request }: Route.LoaderArgs) {   // runs on the server (or client with clientLoader)
  const user = await requireUser(request);
  const order = await db.order.findUnique({ where: { id: params.id, userId: user.id } });
  if (!order) throw new Response("Not found", { status: 404 });
  return { order };
}

export async function action({ request, params }: Route.ActionArgs) {   // handles <Form method="post">
  const form = await request.formData();
  await cancelOrder(params.id, String(form.get("reason")));
  return redirect(`/orders/${params.id}`);
}

export default function Order({ loaderData }: Route.ComponentProps) {
  const { order } = loaderData;
  return (
    <Form method="post">                            {/* works without JS; enhanced with JS */}
      <h1>Order {order.id}</h1>
      <input name="reason" required />
      <button>Cancel order</button>
    </Form>
  );
}

Its philosophy is web standards first (Request/Response, FormData, real forms, HTTP caching headers), parallel loading of nested routes' data (no waterfalls), and automatic revalidation after actions. It supports SSR, SPA mode, and prerendering, with RSC support in progress. Shopify's Hydrogen is built on it.

Astro

Astro is a content-first, islands-based framework. Pages are .astro components (HTML-like with frontmatter scripts) that render to static HTML with zero JS by default. Islands can be React, Vue, Svelte, Solid, Preact or Lit components. It has content collections (typed markdown and MDX, plus data from CMSs with schemas), server islands, view transitions built in, SSG by default with SSR adapters (Node, Vercel, Netlify, Cloudflare), and Actions for type-safe server functions. It's ideal for docs, blogs, marketing and e-commerce storefronts, and less suited to highly interactive app UIs.

SvelteKit

SvelteKit is the framework for Svelte. Svelte is a compiler: components compile to small imperative JS that updates the DOM directly, with no virtual DOM. Svelte 5's runes ($state, $derived, $effect, $props) use signals under the hood. SvelteKit provides file-based routing with +page.svelte, +page.server.ts (load functions and form actions), +layout, +server.ts endpoints, per-route prerender and ssr options, adapters for every host, and progressive enhancement with use:enhance. It produces small bundles and has a well-liked developer experience.

Nuxt

Nuxt is the full-stack framework for Vue. It has file-based routing, auto-imports, useFetch/useAsyncData (SSR-aware data fetching with deduplication and payload transfer), route rules for hybrid rendering per route ('/blog/**': { isr: 3600 }, '/admin/**': { ssr: false }, '/api/**': { cors: true }), the Nitro server engine (deploys to Node, serverless, edge and static), server API routes, and a large module ecosystem. Nuxt joined Vercel in 2025 and remains open source. Vue itself uses signal-like reactivity (ref, computed) and has an experimental compile-time "Vapor mode" without a virtual DOM.

Comparing the frameworks

Next.js React Router (fw) Astro SvelteKit Nuxt
UI library React (RSC) React Any (islands) Svelte Vue
Data model Async Server Components, Server Functions, fetch caching Loaders/actions per route Frontmatter, Actions, content collections load + form actions useFetch/useAsyncData, server routes
Default output SSR/static per route, PPR SSR (or SPA/prerender) Static (SSR optional) SSR (prerender per route) SSR (hybrid route rules)
JS shipped Client components only Full route modules Islands only Small compiled output Full app
Sweet spot Large React apps, mixed static/dynamic Web-standards apps, forms-heavy Content sites Fast, small apps Vue teams

All of them are BFFs (backends for frontends): their server layer can call internal services (your Spring, Go or Rust APIs), aggregate them, keep tokens server-side (chapter 28), and shape data for the UI. Keep business rules in the backend services, and let the framework server handle UI composition.

Next.js in production

App Router: routing, layouts and nested routes

The App Router maps folders to URL segments under app/:

Text
app/
  layout.tsx                 ← root layout (required): <html>, <body>, providers
  page.tsx                   ← "/"
  loading.tsx                ← Suspense fallback for this segment
  error.tsx                  ← error boundary for this segment ("use client")
  not-found.tsx
  (marketing)/               ← route group: organises files without affecting the URL
    pricing/page.tsx         ← "/pricing"
  shop/
    layout.tsx               ← nested layout: persists across /shop/* navigations (state kept)
    page.tsx                 ← "/shop"
    [category]/              ← dynamic segment
      page.tsx               ← "/shop/socks"
      [productId]/page.tsx   ← "/shop/socks/42"
  docs/[...slug]/page.tsx    ← catch-all: /docs/a/b/c
  @modal/(.)photo/[id]/page.tsx   ← parallel + intercepting routes (modal over the list)
  api/orders/route.ts        ← route handler (HTTP endpoint)

Layouts wrap their child segments and don't re-render on navigation between siblings, so a sidebar's scroll position and state survive. Templates (template.tsx) are like layouts but remount on every navigation. Navigation uses <Link> (with prefetching of visible links) or useRouter() in client components. Params arrive as promises in recent versions (const { productId } = await params).

Loading UI and error boundaries

loading.tsx automatically wraps the segment's page in <Suspense fallback={<Loading/>}>, so the shell and layouts render instantly and the page streams in. error.tsx wraps the segment in an error boundary (it must be a client component; it receives error and reset), and global-error.tsx handles the root layout. notFound() and redirect() can be called from server code. Granular <Suspense> boundaries inside pages give finer streaming control than one loading.tsx per route.

Server and client components, server actions and route handlers

Pages and layouts are Server Components by default. Add "use client" only for interactive leaves (chapter 22). Server Functions ("use server") handle mutations from forms and client code, and they're public endpoints, so validate and authorise inside them. Route handlers (app/api/**/route.ts) are plain HTTP endpoints using web Request/Response, for webhooks, third-party callers, mobile clients and streaming:

TypeScript
// app/api/webhooks/payments/route.ts
export async function POST(req: Request) {
  const body = await req.text();
  if (!verifySignature(body, req.headers.get("x-signature"))) return new Response("bad signature", { status: 401 });
  const event = PaymentEvent.parse(JSON.parse(body));                 // Zod (chapter 16)
  await markOrderPaid(event.orderId, event.idempotencyKey);
  revalidateTag(`order-${event.orderId}`);
  return Response.json({ ok: true });
}

Middleware (middleware.ts, renamed proxy.ts in Next.js 16) runs before routing on every matching request. It's for redirects, rewrites, locale detection, A/B testing and coarse auth checks. Don't rely on middleware alone for authorisation. CVE-2025-29927 showed that middleware could be bypassed with a crafted header. Enforce authorisation in the data layer, next to the query.

Caching and revalidation

Next.js caching is powerful, and historically confusing. The layers:

Layer What Where Controlled by
Request memoisation Identical fetch calls deduplicated during one render Server, per request Automatic; React.cache() for non-fetch functions
Data cache Results of fetch / cached functions, persisted across requests and deploys Server fetch(url, { next: { revalidate: 60, tags: ["orders"] } }), "use cache" + cacheLife()/cacheTag() (newer model)
Full route cache Rendered HTML + RSC payload of static routes Server/CDN Static vs dynamic rendering; revalidate; dynamic APIs (cookies(), headers()) make a route dynamic
Router cache RSC payloads of visited/prefetched segments Browser, in memory router.refresh(), staleTimes, revalidation from Server Functions

Defaults changed between versions. Next.js 15 made fetch uncached by default after complaints about stale data, and Next.js 16's Cache Components make caching explicit and opt-in with the "use cache" directive on functions, components or files, plus cacheLife profiles and cacheTag tags. On-demand invalidation: revalidateTag(tag) and revalidatePath(path) (and updateTag for read-your-writes in Server Functions).

The principle is the same as everywhere: cache what's shared and stable, tag it, and invalidate on writes. Never cache per-user responses in shared layers. Watch out for cookies() reads and authentication in layouts, which make whole subtrees dynamic.

Metadata

TypeScript
// Static
export const metadata: Metadata = {
  title: { default: "Shop", template: "%s · Shop" },
  description: "Socks and more",
  openGraph: { images: ["/og.png"] },
  alternates: { canonical: "https://shop.example.com" },
};

// Dynamic, per page
export async function generateMetadata({ params }: { params: Promise<{ productId: string }> }): Promise<Metadata> {
  const { productId } = await params;
  const p = await getProduct(productId);                        // deduplicated with the page's own fetch
  return { title: p.name, description: p.summary, openGraph: { images: [p.image] } };
}

There are also file conventions (sitemap.ts, robots.ts, opengraph-image.tsx for generated OG images, icon.png, manifest.ts) and streaming metadata, so slow generateMetadata calls don't block the first paint for real users.

Image optimisation

next/image wraps <img> with automatic responsive srcset, modern formats (AVIF and WebP, negotiated through the Accept header), lazy loading, reserved dimensions (no CLS), blur placeholders, and an on-demand optimisation server with caching:

TSX
import Image from "next/image";
<Image src={product.image} alt={product.name} width={800} height={600}
       sizes="(min-width: 64rem) 50vw, 100vw" priority={isAboveTheFold} />   // priority / preload for the LCP image

Configure images.remotePatterns to allow-list remote hosts, because an open image optimiser can be abused as a proxy. At scale, optimisation costs CPU, so use a CDN image service (Cloudinary, imgix, Cloudflare Images, Vercel) through a custom loader.

Font optimisation

next/font downloads Google or local fonts at build time and self-hosts them. That removes the third-party connection and the privacy concern. It generates @font-face with font-display: swap, size-adjusted fallback fonts (so the layout doesn't shift when the web font loads, reducing CLS), and preloads only the subsets used:

TSX
import { Inter } from "next/font/google";
const inter = Inter({ subsets: ["latin"], display: "swap", variable: "--font-inter" });
export default function RootLayout({ children }) { return <html lang="en" className={inter.variable}><body>{children}</body></html>; }

Streaming and the deployment runtime

Next.js streams App Router responses by default, using loading.tsx and Suspense. In production, make sure the path from the server to the user doesn't buffer: Nginx proxy_buffering off for those routes, or X-Accel-Buffering: no, and CDN and compression settings that support streaming.

Runtimes: route segments run on the Node.js runtime (the default: full Node APIs and native modules) or the Edge runtime (export const runtime = "edge": Web APIs only, fast cold starts, size limits). Choose Node for database access and most work. Use edge for latency-sensitive logic that doesn't need a far-away database.

Deployment options:

Target How Notes
Vercel git push All features (ISR, PPR, image optimisation, edge) managed
Node server / container output: "standalone" → small Docker image with node server.js You run caching and image optimisation; configure a shared cache handler (Redis) when running several instances
AWS / Cloudflare / Netlify OpenNext adapters Maps features to Lambda/Workers + S3 + CDN
Static output: "export" No SSR, ISR, middleware or Server Functions

For self-hosting across several instances, configure a shared cache handler, so ISR and data caches are consistent between instances. Set deploymentId and version skew protection, so a client running an old build doesn't call a new deployment's Server Functions with mismatched IDs. And put a CDN in front for static assets (chapter 31).

Lab: rendering strategies, measured

Every strategy here was built by hand on a small Node server with React 19's own APIs (renderToString, renderToPipeableStream, hydrateRoot), which is what full-stack frameworks do underneath. Page loads ran in Chromium 153 with CPU slowed 4× and download speed limited to 1.6 Mbit/s through the DevTools protocol, roughly a mid-range Android phone on a poor connection, and the "database" took 300 ms. Each figure is the median of five fresh page loads.

Experiment 1: four strategies, one page

The same menu component (three dishes, an Add button per dish, a cart counter) served four ways:

  • CSR: an empty <div id="root"> and the 224 KB app bundle, which fetches /api/dishes and renders.
  • SSR: the server queries the data, renders HTML with renderToString, embeds the data as JSON, and sends the same bundle to hydrate.
  • SSG: the same HTML rendered once, cached, and served as a file.
  • Islands: the same static HTML, but instead of hydrating the whole page with React, a 203-byte script wires up only the interactive part (the Add buttons and the counter).

The test recorded when the first byte arrived, when the menu appeared, and when clicking Add first updated the cart:

Text
JS sent to the browser: CSR bundle 224086 bytes | SSR hydration bundle 224094 bytes | island script 203 bytes
CSR      first byte    5 ms | menu visible  1677 ms | Add button works  1724 ms
SSR      first byte  306 ms | menu visible   428 ms | Add button works  1718 ms
SSG      first byte    4 ms | menu visible   113 ms | Add button works  1395 ms
ISLANDS  first byte    4 ms | menu visible   129 ms | Add button works   132 ms

Three lessons:

  1. Server rendering moves "visible" earlier: from 1.7 s (CSR) to 0.4 s (SSR, paying the database time up front) or 0.1 s (SSG, paying it at build time). That's what Largest Contentful Paint (chapter 27) rewards.
  2. It doesn't move "interactive" earlier. SSR and SSG pages still needed the full React bundle to download, parse and hydrate before a click did anything: more than a second during which buttons are visible but dead. Users tap them, nothing happens, and they tap again (a "rage click"). The SSR page was actually no faster to interact with than CSR here.
  3. Shipping less JavaScript is what moves "interactive". The islands version made the button work at 132 ms, because it sent 203 bytes instead of 224 KB. That's the idea behind Astro's islands, Qwik's resumability, Angular's incremental hydration and React Server Components: most of a page is content that never needs JavaScript; send code only for the parts that do.

Experiment 2: streaming a slow section

A product page whose reviews come from a service that takes 800 ms. With renderToPipeableStream and <Suspense fallback={<p>Loading reviews…</p>}> around the reviews, the raw response arrived in two chunks (inline scripts abbreviated):

Text
+  34 ms  chunk of  270 bytes: <!DOCTYPE html><html><head></head><body><main><h1>Masala dosa</h1><p>₹90 · crisp, with potato masala</p>
                               <!--$?--><template id="B:0"></template><p>Loading reviews…</p>…
+ 825 ms  chunk of  966 bytes: <div hidden id="S:0"><ul><li>Best in Hyderabad</li><li>Chutney was perfect</li></ul></div><script>…</script></body></html>

Without streaming, the first byte would have waited the full 800 ms. With it, the name and price were on screen in 34 ms. The <!--$?--> comment and <template id="B:0"> mark the pending boundary; the second chunk carries the finished HTML in a hidden <div id="S:0"> and a small script that moves it into place. This works only if nothing in front of the boundary needs the slow data, so where you put Suspense boundaries is a design decision. Two practical notes: proxies and CDNs that buffer responses (some do by default) silently undo streaming, and response headers (status code, cookies) are sent with the first chunk, so a "not found" discovered later can't change the status any more.

Experiment 3: a hydration mismatch

The server rendered Rendered at 09:00:00 am and Hello, guest; the browser's render produced its own time and, because window exists there, Hello, Asha:

Text
console.error: recoverable: Hydration failed because the server rendered text didn't match the client.
               As a result this tree will be regenerated on the client. …
final DOM: Rendered at 2:15:48 pm · Hello, Asha

React recovered by throwing away the server HTML for that tree and rendering it from scratch on the client: correct in the end, but it costs the time SSR was supposed to save, and the content visibly changes. In development the console names the mismatching text. Fixes depend on the cause: format dates on the server and pass the string, render user-specific bits after hydration (useEffect or a client-only component), use useId for generated ids, and keep HTML valid (a <div> inside a <p> is repaired differently by the browser's parser, chapter 12, causing mismatches).

Try it yourself

  1. Add a 300 ms "related dishes" query to experiment 1's SSR page that runs after the menu query. Measure the waterfall, then run the two queries with Promise.all and measure again.
  2. Wrap experiment 2's reviews in a second, nested Suspense boundary with its own slow data. Predict the chunk sequence before running it.
  3. Create a Next.js app (npx create-next-app@latest), make one route static and one dynamic, run next build, and read the route table it prints (○ static, ƒ dynamic). Which of this lab's strategies does each correspond to?
  4. Put Astro's client:visible on a component in an otherwise static page and compare the JavaScript shipped with a fully hydrated version.

Revision sheet: full-stack frameworks

Key ideas

  • Rendering strategies: CSR, SSR, SSG, ISR/revalidation, streaming SSR, partial prerendering (static shell + dynamic holes), islands, Server Components, edge rendering; choose per route.
  • Hydration re-runs components in the browser to attach behaviour; it costs the full JavaScript of every hydrated component; mismatches force client re-rendering.
  • Reducing hydration: islands (Astro), resumability (Qwik), incremental/partial hydration (Angular @defer (hydrate on …)), Server Components (only client components ship JS).
  • React Server Components: run on the server only, can read data directly, render to a serialised payload; "use client" marks interactive leaves; props crossing the boundary must be serialisable; Server Functions ("use server") for mutations.
  • Data loading: route loaders (React Router, SvelteKit, Nuxt), async Server Components (Next.js); avoid request waterfalls by starting queries in parallel and loading at the route level.
  • Caching layers: browser, CDN, framework data cache, full-page cache; revalidate by time or by tag/path; Next.js 16's explicit "use cache" with cacheLife/cacheTag.
  • Runtimes: Node.js servers, serverless functions, edge isolates (fast start, limited APIs, near users but often far from databases).
  • Framework landscape: Next.js (React, RSC-first), React Router v7 framework mode (formerly Remix), Astro (content, islands, any UI library), SvelteKit, Nuxt (Vue), Angular SSR, TanStack Start, Qwik City.

Numbers to remember

  • Lab (throttled phone): menu visible CSR 1.68 s, SSR 0.43 s, SSG 0.11 s; button usable after about 1.4–1.7 s for all hydrated variants vs 0.13 s for an island.
  • Streaming: first chunk at 34 ms vs 800 ms waiting for the slow section.

Pitfalls

  • Treating SSR as a fix for slow interactivity; shipping the whole app's JS to hydrate mostly static pages.
  • Hydration mismatches from dates, randomness, window checks, invalid HTML nesting and extensions.
  • Data waterfalls (parent fetches, then child fetches); fetching in effects after hydration what the server already had.
  • Caching personalised responses at a CDN; forgetting cache invalidation on writes.
  • Putting secrets or heavy server-only code where it can be bundled for the client; leaking data through serialised props.
  • Edge functions calling a database on another continent (each query pays the distance).

Glossary

  • TTFB: time to first byte of the response.
  • Hydration: attaching client behaviour to server-rendered HTML.
  • Island: an independently hydrated interactive component in an otherwise static page.
  • Resumability: continuing the server's execution state in the browser without re-running components.
  • Revalidation: regenerating cached/static output after a time or an event.
  • Suspense boundary: a component boundary that shows a fallback until its contents are ready, and a streaming unit.