Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 50 ยท Framework Mode

Framework Mode Overview

Meet React Router framework mode: the Vite plugin, react-router.config.ts, root.tsx, entry files, and the choice between SSR, SPA mode and prerendering.

Up to now you have built routers by hand: you installed a package, wrote route objects, mounted a RouterProvider and chose a bundler yourself. Framework mode is the third way to use React Router, and it takes most of that work off your hands. A Vite plugin and a small command-line tool wrap the same router you already know and add the pieces a real app needs sooner or later: server rendering, a build that splits code by route, loaders and actions that run on the server, generated TypeScript types and a deployment-ready build.

If you have used Remix, this is its successor: Remix v2 apps upgrade to React Router v7 framework mode with mostly mechanical changes (see Migrating From v5, v6 and Remix). If you are starting fresh, think of framework mode as "data mode plus conventions plus a server". This lesson is a tour, so all the code is read-only; the live examples are small simulations that make the main ideas concrete. For the three modes side by side, see Choosing Between Declarative, Data and Framework Mode.

Creating a project

The official starter creates a working app with the Vite plugin, TypeScript and an example route:

Terminal
# read-only: run these on your own machine
npx create-react-router@latest my-app
cd my-app
npm run dev

The dev server is Vite's, so it starts at http://localhost:5173 by default and updates the browser as you edit. The scripts in package.json map to the react-router command:

Script Command What it does
dev react-router dev Starts the dev server with hot reloading
build react-router build Builds the client and (with SSR) the server
start react-router-serve ./build/server/index.js Serves the production build with the bundled Node server
typecheck react-router typegen && tsc Generates route types, then checks them

The project layout

A fresh project looks like this:

TEXT
my-app/
  app/
    routes/
      home.tsx          a route module
    entry.client.tsx    optional: hydrates the page in the browser
    entry.server.tsx    optional: renders the page on the server
    root.tsx            the root route and the HTML document
    routes.ts           the route config
  public/               static files served as they are
  react-router.config.ts
  vite.config.ts
  tsconfig.json

Only four things are required: app/root.tsx, app/routes.ts, the Vite config with the plugin, and the route modules themselves. The two entry files are optional, because the framework supplies defaults. Run npx react-router reveal when you want a copy of them to customize.

Click any file in the explorer to see what it is for and whether you can delete it.

Real library or stand-in? The code and commands in this lesson are the real framework-mode API, shown read-only because the live editor cannot run Vite, Node or a server. The two examples below are small hand-written simulations in React: a file explorer with descriptions, and a decision table that applies the documented rendering rules to a few URLs. They teach the concepts and do not run the real build.

Explore a framework-mode project

The Vite plugin and the config file

Framework mode is switched on by one line in vite.config.ts:

TypeScript
// vite.config.ts (read-only)
import { reactRouter } from '@react-router/dev/vite';
import { defineConfig } from 'vite';

export default defineConfig({
  plugins: [reactRouter()],
});

Framework settings live in a separate file, so Vite settings and router settings never mix:

TypeScript
// react-router.config.ts (read-only)
import type { Config } from '@react-router/dev/config';

export default {
  appDirectory: 'app',   // where root.tsx and routes.ts live
  ssr: true,             // render on the server (the default)
  async prerender() {
    return ['/', '/about']; // also render these pages once, at build time
  },
} satisfies Config;

You will rarely need more than ssr and prerender. Others include basename (serve the app under a sub-path) and buildDirectory, and a future object for opting in to upcoming behavior early.

root.tsx: the document and the root route

In data mode, your HTML lived in index.html. In framework mode the root route renders the whole document, so that the server can send complete HTML:

TSX
// app/root.tsx (read-only)
import { Links, Meta, Outlet, Scripts, ScrollRestoration } from 'react-router';

export function Layout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <head>
        <meta charSet="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <Meta />
        <Links />
      </head>
      <body>
        {children}
        <ScrollRestoration />
        <Scripts />
      </body>
    </html>
  );
}

export default function App() {
  return <Outlet />;
}

<Meta /> and <Links /> render whatever the active route modules export as meta and links. <ScrollRestoration /> is the component from Scroll Restoration, Focus and Page Titles, and <Scripts /> adds the JavaScript that makes the page interactive. Layout also wraps your ErrorBoundary, so errors render inside a valid document.

The entry files

Two optional files control the edges of the app:

TSX
// app/entry.client.tsx (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>,
  );
});

entry.client.tsx is where you would add things such as an error reporter that must start before React. entry.server.tsx exports a handleRequest function that receives the request and the router context and returns a Response; the default renders <ServerRouter> to a stream. Most apps never touch either file.

flowchart LR
    A["Browser requests /products/42"] --> B["entry.server.tsx<br/>handleRequest"]
    B --> C["Run loaders<br/>of matched routes"]
    C --> D["Render root.tsx and route modules<br/>to HTML"]
    D --> E["HTML response<br/>visible at once"]
    E --> F["entry.client.tsx<br/>hydrateRoot"]
    F --> G["Page is interactive<br/>client-side navigation"]

On the first visit the server does the heavy lifting; after hydration, link clicks are handled in the browser like in data mode.

SSR, SPA mode and prerendering

Framework mode does not force you to run a server. A single setting chooses the rendering strategy:

  • SSR (ssr: true, the default): the server renders HTML for every request. Pages arrive complete, which helps both first paint and search engines, and loader and action run on the server. You need a server runtime (Node, Cloudflare Workers and so on).
  • SPA mode (ssr: false): the build produces static files. The root route is rendered at build time into index.html, and the browser renders every page. You can host it anywhere static files can go. Server loaders and actions are not allowed; use clientLoader and clientAction.
  • Prerendering (prerender): the build renders chosen URLs to static HTML once. It combines with either mode. With ssr: true, the listed pages are static and the rest are rendered on demand. With ssr: false, the listed pages are static and every other URL falls back to the SPA shell. The value true prerenders every route without dynamic segments, and a list or an async function names exactly the URLs you want, including dynamic ones such as /products/42.

Use the controls to apply these rules to some URLs. The output follows the rules above; it is not a measurement.

When is each page's HTML created?

Switch ssr off and choose "a list": the two listed pages become files, while /products/42 is rendered by the browser. Set the list while ssr is on, and the product page is rendered per request. Choose true and notice that the product page is not covered, because true only handles URLs without dynamic segments.

What changes compared with data mode

Topic Data mode Framework mode
Setup You pick the bundler and mount RouterProvider reactRouter() Vite plugin and the react-router CLI
Routes Route objects in your code app/routes.ts that points to route module files
Route code loader, action and Component as properties The same names as exports of a route module
Where loaders run In the browser On the server (loader) or in the browser (clientLoader)
HTML document Your own index.html root.tsx renders it, so the server can send it
Page <head> Your own code and effects meta, links and headers exports
Code splitting You add lazy yourself Automatic, one chunk per route module
Types You write them Generated for each route (Route.LoaderArgs, Route.ComponentProps)
Deploy Static files A Node server, a platform adapter, or static files in SPA mode

Most of what you learned in Data Mode carries over unchanged: nested routes with an Outlet, params, search params, Link, Form, fetchers, redirect, error boundaries and useNavigation. What changes is where the code lives and where it runs. A route module in framework mode looks like this:

TSX
// app/routes/home.tsx (read-only)
import type { Route } from './+types/home';

export function meta({}: Route.MetaArgs) {
  return [{ title: 'Home | My App' }];
}

export async function loader({ params }: Route.LoaderArgs) {
  return { greeting: 'Hello from the server' };
}

export default function Home({ loaderData }: Route.ComponentProps) {
  return <h1>{loaderData.greeting}</h1>;
}

The ./+types/home import is a generated file; the next lesson, Route Config and File Routes, explains how it appears and how routes.ts connects URLs to files.

When to choose it

Choose framework mode when you want server rendering or prerendering for SEO and fast first paint, when you want the framework to handle bundling and code splitting, or when your loaders need a database and secrets that must never reach the browser. Stay in data mode when you already have a client-rendered app and a bundler setup you like, or when a static index.html is all you need. You can move from data mode to framework mode later, because the routing concepts are the same.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which line turns on framework mode in a project?

    The @react-router/dev/vite plugin provides route config handling, code splitting and the build. The other options are declarative or data mode setups.
  2. 2. What is the main job of root.tsx in framework mode?

    The root route exports Layout, which returns the full <html> document, and a default component with an Outlet. Every other route renders inside it.
  3. 3. You set ssr: false and do not set prerender. How is a page like /about displayed?

    SPA mode builds static files and the browser renders the pages. Only the root route is rendered at build time, into index.html.
  4. 4. Which of these is NOT allowed when ssr is false?

    Without a server there is nowhere to run a server loader or action at request time. Use clientLoader and clientAction instead.
  5. 5. Do you have to write entry.client.tsx and entry.server.tsx yourself?

    Both files are optional. The framework ships default versions, and the reveal command copies them into your project for customization.

Summary

  • Framework mode is React Router plus a Vite plugin, a CLI, conventions and a server: the same routing ideas, with more built in.
  • Required files: vite.config.ts with reactRouter(), app/root.tsx, app/routes.ts and your route modules; entry files and react-router.config.ts are optional.
  • root.tsx renders the whole HTML document (Layout) and is the parent of every route.
  • ssr: true renders on the server, ssr: false produces a static SPA, and prerender renders chosen URLs to files at build time.
  • Route modules export loader, action, meta, links and a default component; types are generated for you.
  • Navigation after the first load works as in data mode, in the browser.

Next: Route Config and File Routes