Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 50 ยท Framework Mode

SSR, Streaming and Deployment

Understand server rendering in React Router framework mode: streaming with Await, prerendering, SPA mode, deploying to Node, Cloudflare or static hosts, SEO basics and Remix upgrades.

A plain single-page app sends an almost empty HTML file and a large JavaScript bundle. The browser must download, parse and run that bundle, then fetch data, and only then can the user read anything. Search engines and link-preview bots often see the empty shell. Server-side rendering (SSR) fixes both problems: the server runs your routes and sends finished HTML, and JavaScript then hydrates the page to make it interactive.

React Router's framework mode gives you SSR by default and lets you dial it up or down per project: render every request on a server, prerender chosen pages at build time, or ship a pure single-page app. This lesson explains the three strategies, how streaming keeps slow data from blocking the page, what the build produces, where you can deploy it and what changes for SEO. It continues Server Loaders, Client Loaders and Actions. As in the other framework-mode lessons, the real configuration and entry files are read-only, and the live examples are stand-ins built on React alone.

Three ways to render a route

A single flag and a list in react-router.config.ts choose the strategy:

TypeScript
// react-router.config.ts - React Router framework mode (read-only)
import type { Config } from "@react-router/dev/config";

export default {
  // true (default): render on a server for every request
  // false: build a single-page app, no server runtime
  ssr: true,

  // optional: render these URLs to static HTML files at build time
  async prerender() {
    return ["/", "/about", "/pricing"];
  },
} satisfies Config;
Setting When HTML is made Needs a server at runtime Good for
ssr: true on every request yes personalized or frequently changing pages
ssr: true plus prerender at build time for listed URLs, on request for the rest yes marketing pages next to a dynamic app
ssr: false plus prerender at build time for listed URLs no (static files) docs, blogs, landing pages
ssr: false never (empty shell, browser renders) no (static files) dashboards behind a login

prerender: true prerenders every route whose path has no dynamic segments. A function can return explicit URLs, including ones you build from a database or a list of files, such as every blog post slug. During prerendering the loaders run once, at build time, and their output is saved into the HTML and data files, so the data is only as fresh as the last build.

The first example makes the difference tangible. It renders the same product component with the real renderToString from react-dom/server to show the first bytes each mode would deliver for a URL. The "server" part is imitated by plain functions.

What does the first response contain?

Try /products/2 in each mode. With plain SSR the heading and price are already inside <div id="root">. With prerendering, listed URLs are static HTML and unlisted ones fall back to the empty shell, which the browser fills in later (when ssr is false and / is not prerendered, React Router writes a __spa-fallback.html file for hosts to use as the "not found" page). The real framework uses its own prerender step, not renderToString, but the idea is the same: the loader data and the component are turned into HTML ahead of the browser.

What the server actually does

For each document request in SSR mode, the server matches the URL against the route tree, runs the matched loaders in parallel, renders the components with that data and sends the HTML. Hydration then runs on the client with the same route tree and the same data, so the markup must match.

sequenceDiagram
    participant B as Browser
    participant S as Server
    B->>S: GET /products/2
    S->>S: match routes, run loaders
    S->>S: render React to HTML
    S-->>B: HTML (readable at once)
    B->>B: download JavaScript
    B->>B: hydrate (page becomes interactive)
    Note over B: later clicks are client navigations, no full reload

The user can read the page after the HTML arrives. Hydration only adds interactivity.

Two small files control this, and the framework generates defaults if you do not create them (run npx react-router reveal to copy them into your project):

TSX
// app/entry.server.tsx - React Router framework mode (read-only, shortened)
import { renderToPipeableStream } from "react-dom/server";
import { ServerRouter } from "react-router";

// handleRequest decides how the HTML stream starts. Bots get "onAllReady"
// (wait for everything), people get "onShellReady" (start streaming early).
export default function handleRequest(request, status, headers, routerContext) {
  /* create a PassThrough stream, call renderToPipeableStream(
       <ServerRouter context={routerContext} url={request.url} />,
       { onShellReady() { ... pipe(body) ... } }
     ), then resolve with new Response(body, { status, headers }) */
}
TSX
// app/entry.client.tsx - React Router framework mode (read-only)
import { startTransition, StrictMode } from "react";
import { hydrateRoot } from "react-dom/client";
import { HydratedRouter } from "react-router/dom";

startTransition(() => {
  hydrateRoot(document, <StrictMode><HydratedRouter /></StrictMode>);
});

Most apps never edit these files. You customize them to add analytics, wrap providers around the router, tune the stream timeout or integrate a different server runtime.

Streaming slow data

A loader that awaits a slow query delays everything, because HTML cannot start until all loaders have finished. The fix is to await only the data the page needs immediately and return the slow part as an unawaited promise. React Router streams the shell first and sends the promise's result later, in the same HTTP response:

TSX
// app/routes/product.tsx - React Router framework mode (read-only)
import { Suspense } from "react";
import { Await } from "react-router";

export async function loader({ params }: Route.LoaderArgs) {
  const product = await db.product.find(params.id);   // needed now: awaited
  const reviews = db.review.listFor(params.id);       // slow: a promise, not awaited
  return { product, reviews };
}

export default function Product({ loaderData }: Route.ComponentProps) {
  const { product, reviews } = loaderData;
  return (
    <main>
      <h1>{product.name}</h1>
      <Suspense fallback={<p>Loading reviews...</p>}>
        <Await resolve={reviews} errorElement={<p>Could not load reviews.</p>}>
          {(list) => <ReviewList reviews={list} />}
        </Await>
      </Suspense>
    </main>
  );
}

The stream contains the page with the fallback first, then a small chunk that swaps in the real content when the promise settles. React 19 code can also read the promise with use() instead of <Await>. The data-mode version of the same idea is in Streaming Data with Await and Suspense.

flowchart LR
    A["loader starts both queries"] --> B["product ready (awaited)"]
    A --> C["reviews still pending (promise)"]
    B --> D["server sends HTML shell with fallback"]
    C --> E["promise settles"]
    D --> F["browser shows the page at once"]
    E --> G["server streams the reviews chunk"]
    F --> H["fallback is replaced"]
    G --> H

Awaiting only what the page shell needs moves the first paint earlier; the rest arrives while the user is already reading.

The next stand-in uses React's use() and a slow fake "query" (800 ms) so you can feel the difference between waiting for everything and streaming. The real router streams it over HTTP, while here both pieces live in the browser.

Await everything, or stream the slow part

With "await everything" the whole area stays blank for 800 ms, then the full page appears. With "stream reviews" the title shows immediately and only the review list waits behind a fallback. Stream data that is slow and not essential for the first screen, such as reviews, recommendations or analytics. Do not stream the content search engines must index immediately, such as the article body.

Build output

react-router build compiles your app twice, one bundle for browsers and one for the server:

flowchart TD
    A["react-router build"] --> B["build/client<br/>JS, CSS, images, prerendered HTML"]
    A --> C["build/server<br/>index.js, the request handler"]
    B --> D["static hosts and CDNs"]
    B --> E["served by your Node server or edge worker"]
    C --> E

With ssr: false there is no build/server folder to run: build/client alone is the site.

The scripts of a typical project are react-router dev (development with hot reload), react-router build and react-router-serve ./build/server/index.js (a ready-made Node server from @react-router/serve). In SPA mode, the build writes an index.html into build/client. A route may not export a server loader or action when ssr is false, because there is no server to run it (prerendered routes are the exception: their loaders run at build time). Use clientLoader and clientAction instead.

Deploying

Because the output is standard (Web Request and Response objects), many hosts work:

  • Node server. The simplest: build, copy the files and run react-router-serve, or use your own Express, Fastify or Hono server with the request handler from build/server. A Dockerfile that installs production dependencies, copies build/ and runs the start script is enough. Put a reverse proxy or CDN in front and serve build/client/assets with long cache headers, since those file names contain content hashes.
  • Edge and serverless platforms. Cloudflare Workers, Vercel, Netlify and similar hosts run the server bundle as a function. Each platform has an official template or preset (for example the Cloudflare template using the Vite plugin) that adds the right entry file. The platform's bindings, such as a key-value store or database, reach your loaders through the load context, and platforms with no Node APIs mean you must avoid Node-only imports.
  • Static hosts. With ssr: false, upload build/client to S3 and CloudFront, GitHub Pages, Netlify or any file host. Tell the host to answer unknown paths with index.html (or __spa-fallback.html) and status 200 so deep links work.

Environment variables are read on the server (process.env, or the platform's bindings). Anything you want in the browser must be passed explicitly through a loader or Vite's import.meta.env.VITE_* variables, which are public by design.

SEO considerations

SSR and prerendering give crawlers real HTML, but you still have to describe each page:

  • Export a meta function per route with a unique title and description, built from loader data.
  • Make loaders throw data(..., { status: 404 }) when a record does not exist, so the server sends a real 404 status instead of a soft 404. See 404 Pages and Catch-All Routes.
  • Add a canonical <link> through links or meta for pages reachable with several URLs.
  • Serve sitemap.xml and robots.txt from resource routes: route modules with a loader and no default component that return a Response.
  • Keep important content out of the streamed (deferred) parts and avoid client-only rendering for it.
TypeScript
// app/routes/sitemap.ts - React Router framework mode (read-only)
export async function loader() {
  const urls = (await db.post.allSlugs()).map((slug: string) => "https://example.com/blog/" + slug);
  const body =
    '<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' +
    urls.map((u: string) => "<url><loc>" + u + "</loc></url>").join("") +
    "</urlset>";
  return new Response(body, { headers: { "Content-Type": "application/xml" } });
}

Upgrading from Remix

React Router 7 is the next version of Remix, merged into one library. If you have a Remix 2 app, the upgrade is mostly mechanical: turn on the Remix future flags first, then replace the @remix-run/* packages with react-router and @react-router/* equivalents, swap RemixServer for ServerRouter and RemixBrowser for HydratedRouter, replace the Vite plugin with @react-router/dev/vite, and move route config into routes.ts. A codemod handles most imports. Loaders can now return plain objects, so json() and defer() are no longer needed. The complete checklist is in Migrating From v5, v6 and Remix.

Choosing the right strategy is a small decision. The last example encodes the rules of thumb from this lesson so you can test your own project against them.

Which rendering strategy fits?

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does hydration do after the server has sent the HTML?

    The browser already shows the server's HTML. Hydration runs your components with the same data and wires up event handlers, without rebuilding the DOM.
  2. 2. Which setting produces plain static files and needs no server at runtime?

    With ssr set to false the build output is static files in build/client. prerender additionally writes real HTML for the URLs you list.
  3. 3. Why return a slow query as an unawaited promise from a loader?

    An awaited loader blocks the whole response. A pending promise lets React Router send the shell immediately and stream the promise's result in the same response.
  4. 4. A product page matches /products/:id but the record is missing. How do you get a real 404 status for search engines?

    What the component shows does not change the HTTP status. A loader that throws data(..., { status: 404 }) makes the server answer 404 and renders the error boundary.
  5. 5. When ssr is false, what is true about a server loader export on a route that is not prerendered?

    SPA mode ships no server runtime. Only prerendered routes may use server loaders, and then they run once at build time.

Summary

  • Framework mode renders on a server by default (ssr: true); ssr: false builds a single-page app and prerender writes chosen pages to static HTML at build time.
  • Hydration makes the server's HTML interactive, and later navigations happen in the browser.
  • Await only what the first screen needs and return slow data as a promise, then show it with Suspense and Await (or use).
  • react-router build produces build/client and build/server; deploy to Node, edge platforms or, in SPA and prerendered setups, a static host with a fallback to the shell.
  • For SEO, give every route its own meta, throw real 404 responses from loaders and serve sitemaps from resource routes.
  • Remix 2 apps upgrade by renaming packages and entry components; plain objects replace json() and defer().

Next: Testing Routes and Components