Skip to main content

Web frameworks · Intermediate · 26 min

Build a server-rendered app with React Router framework mode

By Padding · Updated 18 Nov 2026
Node.js 26 · React Router 8.5.2 · React 19.3

You will build a server-rendered notes app with React Router 8.5 framework mode, with file-based routes, server loaders and actions, a form that works before JavaScript loads, validation errors and page titles, and run its production build with react-router-serve on Node.js.

On this page

React Router has three modes. In declarative and data mode it is a routing library you add to a single-page app. In framework mode, React Router is the framework itself, the line of work that used to be called Remix. It renders every page on the server, runs a loader function on the server before a page renders and an action function when a form posts, splits the JavaScript per route, and builds a Node.js server for production.

You will build a small notes app: a home page that counts notes, a notes layout with a sidebar list, one page per note, and a form that creates notes. The form is a real HTML form, so it saves notes even when the JavaScript has not downloaded yet. That matters on a low-end Android phone on a slow or prepaid connection, where the page can be on screen for several seconds before the scripts arrive. The tutorial assumes Node.js 26 from the Node.js install tutorial and works the same on Linux and macOS.

Step 1 · Create the project

create-react-router copies the official default template and installs its dependencies. --yes accepts the defaults without asking, and --no-git-init leaves Git for you to set up when you want it. The version is pinned so the files match what this tutorial describes:

Bash
cd ~
npx -y create-react-router@8.5.2 rr-notes-demo --yes --no-git-init
cd rr-notes-demo

With --yes the tool also adds an .agents/ folder that teaches AI coding assistants about React Router. It does nothing at runtime, and you can delete it.

Check it worked

The command ends with That's it!. Look at the configuration and scripts:

Bash
cat react-router.config.ts
grep -A 5 '"scripts"' package.json

react-router.config.ts contains ssr: true, which is what makes this a server-rendered app. Set it to false and the same project builds as a single-page app. The scripts are build (react-router build), dev (react-router dev), start (react-router-serve ./build/server/index.js) and typecheck. The dependencies include react-router, @react-router/node and @react-router/serve at 8.5, and @react-router/dev under devDependencies. The template also comes with Tailwind CSS, which the class names later in this tutorial use.

Step 2 · Run the development server

Start the dev server in your second terminal, from the rr-notes-demo folder, and leave it running:

Bash
npm run dev

It prints Local: http://localhost:5173/. In your first terminal, ask for the home page and pick out the title:

Bash
curl -s http://localhost:5173/ | grep -o '<title>[^<]*</title>'

Check it worked

The output is <title>New React Router App</title>. That title comes from the meta function in app/routes/home.tsx, and it is already in the HTML the server sent. A Vite single-page app sends an empty <div id="root"> and builds the page in the browser. Framework mode sends the finished page, then loads JavaScript to make it interactive. That second part is called hydration.

Stop the dev server with Ctrl+C now, because the next step changes how routes are found.

Step 3 · Switch to file-based routes

The template lists routes by hand in app/routes.ts. That is fine for a few pages. Here you switch to file-based routing, where the files in app/routes/ are the routes. Install the package that reads the folder:

Bash
npm install @react-router/fs-routes@8.5.2

Replace app/routes.ts, and remove the starter page and its welcome component:

Bash
cat > app/routes.ts <<'TS'
import { type RouteConfig } from "@react-router/dev/routes";
import { flatRoutes } from "@react-router/fs-routes";

export default flatRoutes() satisfies RouteConfig;
TS
rm -rf app/routes/home.tsx app/welcome

The app needs somewhere to keep notes. A JSON file on disk is enough to learn with. Put the code that reads and writes it in a file whose name ends in .server.ts. React Router keeps .server modules out of the browser bundle, and the build fails if one is imported by code that would run in the browser. Database clients and secrets belong in files like this:

Bash
cat > app/notes.server.ts <<'TS'
import { mkdir, readFile, writeFile } from "node:fs/promises";

export type Note = { id: string; title: string; body: string; createdAt: string };

const FILE = "data/notes.json";

export async function listNotes(): Promise<Note[]> {
  try {
    return JSON.parse(await readFile(FILE, "utf8"));
  } catch {
    return [];
  }
}

export async function getNote(id: string) {
  const notes = await listNotes();
  return notes.find((note) => note.id === id) ?? null;
}

export async function createNote(title: string, body: string) {
  const notes = await listNotes();
  const note: Note = {
    id: crypto.randomUUID().slice(0, 8),
    title,
    body,
    createdAt: new Date().toISOString(),
  };
  await mkdir("data", { recursive: true });
  await writeFile(FILE, JSON.stringify([note, ...notes], null, 2));
  return note;
}
TS

Now the home page. _index.tsx at the top of app/routes/ matches /. Its loader runs on the server for every request, and whatever it returns arrives in the component as loaderData. The Route types come from files that React Router generates for each route, so loaderData.count is typed as a number without you writing that type:

Bash
cat > app/routes/_index.tsx <<'TSX'
import { Link } from "react-router";
import type { Route } from "./+types/_index";
import { listNotes } from "../notes.server";

export function meta({}: Route.MetaArgs) {
  return [
    { title: "Notes" },
    { name: "description", content: "A small server-rendered notes app." },
  ];
}

export async function loader() {
  const notes = await listNotes();
  return { count: notes.length };
}

export default function Home({ loaderData }: Route.ComponentProps) {
  return (
    <main className="mx-auto max-w-xl p-6">
      <h1 className="text-2xl font-bold">Notes</h1>
      <p className="mt-2">{`You have ${loaderData.count} ${loaderData.count === 1 ? "note" : "notes"}.`}</p>
      <Link className="underline" to="/notes">Open your notes</Link>
    </main>
  );
}
TSX
npm run typecheck

npm run typecheck generates the route types, then runs the TypeScript compiler. Run it whenever you add a route file.

Check it worked

The type check prints nothing after its command lines. Start npm run dev again in the second terminal and leave it running for the next steps.

Bash
curl -s http://localhost:5173/ | grep -o 'You have [0-9]* notes*\.'

The output is You have 0 notes., rendered on the server from the loader's data.

Step 4 · Add a layout with a list of notes

In file-based routing, a dot in a file name becomes a slash in the URL, and a file nests inside the file whose name comes before the dot. notes.tsx is the layout for everything under /notes, and its <Outlet /> is where the child page renders. notes._index.tsx is the child shown at /notes itself:

Bash
cat > app/routes/notes.tsx <<'TSX'
import { Link, NavLink, Outlet } from "react-router";
import type { Route } from "./+types/notes";
import { listNotes } from "../notes.server";

export async function loader() {
  const notes = await listNotes();
  return { notes: notes.map(({ id, title }) => ({ id, title })) };
}

export default function NotesLayout({ loaderData }: Route.ComponentProps) {
  return (
    <div className="mx-auto grid max-w-3xl gap-6 p-6 sm:grid-cols-[12rem_1fr]">
      <nav aria-label="Notes">
        <Link className="font-bold" to="/notes/new">New note</Link>
        <ul className="mt-4 space-y-1">
          {loaderData.notes.map((note) => (
            <li key={note.id}>
              <NavLink
                to={`/notes/${note.id}`}
                className={({ isActive }) => (isActive ? "font-bold" : "underline")}
              >
                {note.title}
              </NavLink>
            </li>
          ))}
        </ul>
      </nav>
      <main>
        <Outlet />
      </main>
    </div>
  );
}
TSX
cat > app/routes/notes._index.tsx <<'TSX'
export default function NotesIndex() {
  return <p>Pick a note, or write a new one.</p>;
}
TSX
npm run typecheck

The layout's loader returns only the IDs and titles. Everything a loader returns is serialised into the page for hydration, so sending less keeps pages small, which readers on metered data will notice.

Check it worked

Bash
curl -s http://localhost:5173/notes | grep -o 'Pick a note[^<]*'

The output is Pick a note, or write a new one. In a browser, /notes shows the New note link on the left and that sentence on the right. You did not restart anything: the dev server watches app/routes/ and adds a route as soon as you save a new file there.

Step 5 · Load one note and handle a missing one

$noteId in a file name is a URL parameter, read in the loader as params.noteId. When the note does not exist, the loader throws a response made with data() and a 404 status. React Router then renders the nearest ErrorBoundary in place of the page, inside the layout, and the server sends a real 404 status. The meta function sets a title from the loaded note. The single quotes around the file name stop the shell reading $noteId as a variable:

Bash
cat > 'app/routes/notes.$noteId.tsx' <<'TSX'
import { data, isRouteErrorResponse, Link } from "react-router";
import type { Route } from "./+types/notes.$noteId";
import { getNote } from "../notes.server";

export async function loader({ params }: Route.LoaderArgs) {
  const note = await getNote(params.noteId);
  if (!note) {
    throw data("Note not found", { status: 404 });
  }
  return { note };
}

export function meta({ loaderData }: Route.MetaArgs) {
  const title = loaderData?.note.title ?? "Note not found";
  return [{ title: `${title} · Notes` }];
}

export default function NoteRoute({ loaderData }: Route.ComponentProps) {
  const { note } = loaderData;
  return (
    <article>
      <h1 className="text-xl font-bold">{note.title}</h1>
      <p className="mt-1 text-sm">{new Date(note.createdAt).toUTCString()}</p>
      <p className="mt-4 whitespace-pre-wrap">{note.body}</p>
    </article>
  );
}

export function ErrorBoundary({ error }: Route.ErrorBoundaryProps) {
  if (isRouteErrorResponse(error) && error.status === 404) {
    return (
      <div>
        <h1 className="text-xl font-bold">That note does not exist</h1>
        <Link className="underline" to="/notes">Back to your notes</Link>
      </div>
    );
  }
  return <p>Something went wrong loading this note.</p>;
}
TSX
npm run typecheck

Check it worked

There are no notes yet, so any ID is missing. Ask for one and print the status code, then the page title:

Bash
curl -s -o /dev/null -w '%{http_code}\n' http://localhost:5173/notes/abc123
curl -s http://localhost:5173/notes/abc123 | grep -o '<title>[^<]*</title>\|That note does not exist'

The first command prints 404. The second prints <title>Note not found · Notes</title> and That note does not exist. The sidebar still renders, because the error boundary replaces only the note, not the layout.

Step 6 · Create notes with a form and an action

notes.new.tsx matches /notes/new. A static segment such as new wins over $noteId, so it is not read as a note ID. The action runs on the server when the form posts. It returns validation errors with data() and a 400 status, and redirects to the new note on success.

<Form method="post"> from React Router renders a plain <form>. Before JavaScript loads, the browser posts it the normal way and the server renders the response. Once JavaScript has loaded, React Router sends the post with fetch, runs the action, then reloads the data of every route on the page, so the sidebar list updates on its own. useNavigation reports what is happening, which lets the button say Saving... while the post is on its way:

Bash
cat > app/routes/notes.new.tsx <<'TSX'
import { data, Form, redirect, useNavigation } from "react-router";
import type { Route } from "./+types/notes.new";
import { createNote } from "../notes.server";

export function meta({}: Route.MetaArgs) {
  return [{ title: "New note · Notes" }];
}

export async function action({ request }: Route.ActionArgs) {
  const form = await request.formData();
  const title = String(form.get("title") ?? "").trim();
  const body = String(form.get("body") ?? "").trim();

  const errors: { title?: string; body?: string } = {};
  if (title.length < 3) errors.title = "Give the note a title of at least 3 characters.";
  if (body.length === 0) errors.body = "Write something in the note.";
  if (Object.keys(errors).length > 0) {
    return data({ errors, values: { title, body } }, { status: 400 });
  }

  const note = await createNote(title, body);
  return redirect(`/notes/${note.id}`);
}

export default function NewNote({ actionData }: Route.ComponentProps) {
  const navigation = useNavigation();
  const saving = navigation.state === "submitting";
  const errors = actionData?.errors;

  return (
    <Form method="post" className="grid gap-3">
      <h1 className="text-xl font-bold">New note</h1>
      <label className="grid gap-1">
        Title
        <input
          name="title"
          defaultValue={actionData?.values.title}
          aria-invalid={errors?.title ? true : undefined}
          aria-describedby={errors?.title ? "title-error" : undefined}
          className="border p-2"
        />
      </label>
      {errors?.title ? <p id="title-error" role="alert">{errors.title}</p> : null}
      <label className="grid gap-1">
        Note
        <textarea
          name="body"
          rows={5}
          defaultValue={actionData?.values.body}
          aria-invalid={errors?.body ? true : undefined}
          aria-describedby={errors?.body ? "body-error" : undefined}
          className="border p-2"
        />
      </label>
      {errors?.body ? <p id="body-error" role="alert">{errors.body}</p> : null}
      <button type="submit" disabled={saving} className="border p-2 font-bold">
        {saving ? "Saving..." : "Save note"}
      </button>
    </Form>
  );
}
TSX
npm run typecheck

Points worth knowing:

  • The action sends back the values the reader typed, so a failed post does not wipe out a long note.
  • The 400 status is deliberate. Only a 2xx action response makes React Router reload the page's loaders, so a failed validation costs no extra requests.
  • The form has no required attributes, so you can see the server check work. In a real form, add them too for instant feedback, but always keep the server check, because anyone can post to the URL directly.
  • In production, React Router refuses an action whose Origin header names a different site from the request, as a defence against cross-site request forgery. If your app sits behind a proxy that changes the host, list the allowed origins with allowedActionOrigins in react-router.config.ts.

Check it worked

curl runs no JavaScript, so it posts the form exactly as a browser does before the scripts load. Post an empty title first, then a valid note:

Bash
curl -s -o /dev/null -w '%{http_code}\n' -X POST -d 'title=&body=' http://localhost:5173/notes/new
curl -s -X POST -d 'title=Hi&body=' http://localhost:5173/notes/new | grep -o 'Give the note a title of at least 3 characters\.' | head -1
curl -s -i -X POST --data-urlencode 'title=Market list' --data-urlencode 'body=Tomatoes, rice, pepper' http://localhost:5173/notes/new | grep -i '^location'

The first command prints 400. The second prints Give the note a title of at least 3 characters. The message is in the page twice, once in the HTML and once in the data the page carries for hydration, so head -1 keeps the first. The third prints a header such as location: /notes/3f9c1a2b, with your note's own ID. Open that note's page and check its title:

Bash
NOTE_ID=$(node -p "JSON.parse(require('node:fs').readFileSync('data/notes.json', 'utf8'))[0].id")
curl -s "http://localhost:5173/notes/$NOTE_ID" | grep -o '<title>[^<]*</title>'

The output is <title>Market list · Notes</title>. In a browser, go to /notes/new, open the developer tools, set network throttling to a slow preset such as 3G, and save a note: the button reads Saving... until the server answers, then the new note appears both in the page and in the sidebar. Then switch JavaScript off in the developer tools settings, reload, and save another note. It still works, with a full page load in place of the client-side update. Use the browser's back button afterwards: each page has its own URL, so back and forward and copied links all land on the right note.

Step 7 · Build and run the production server

Stop the dev server with Ctrl+C. Then build the app:

Bash
npm run build
ls build build/client/assets

The build makes two bundles. build/client/ holds the browser JavaScript and CSS, with a hash in each file name so they can be cached for a long time. build/server/index.js is the server code: every loader, action and component, ready to render pages.

Start the production server in the second terminal:

Bash
npm start

npm start runs react-router-serve, a small Express server from @react-router/serve that serves build/client/ as static files and sends every other request to your app. It listens on port 3000, or the next free port if 3000 is taken, and it prints the address. Set PORT=8080 or HOST=127.0.0.1 in its environment to change the port or the address it listens on. To run it on a server you need the build/ folder, package.json, the lock file and npm ci --omit=dev. The template's Dockerfile does the same steps, if you deploy with Docker.

Check it worked

Bash
curl -s http://localhost:3000/ | grep -o 'You have [0-9]* notes*\.'
curl -s -o /dev/null -w '%{http_code}\n' http://localhost:3000/notes/does-not-exist

The first command prints the number of notes you have saved, such as You have 3 notes., rendered by the production server. The second prints 404. Notes live in data/notes.json in the folder you start the server from, so they survive a restart. For anything beyond learning, swap the body of notes.server.ts for a real database: no route file needs to change.

Step 8 · Compare, then clean up

You have now used each part of framework mode once. Here is how it sits next to the two closest choices.

Framework mode and data mode

Data mode uses the same loader, action, <Form>, useNavigation and error boundaries, but you build it into a Vite single-page app with createBrowserRouter, and the loaders run in the browser. There is no server rendering unless you build it yourself, and secrets cannot live in a loader. Choose data mode for an app behind a login that does not need search engines or a fast first paint, and that you want to host as static files. Choose framework mode when the first view must arrive as HTML, when forms must work before JavaScript loads, or when you want server code next to the page that uses it. Moving from data mode to framework mode is mostly moving route objects into route modules.

Framework mode and Next.js

Next.js 16 also renders on the server and routes by file, but its model is React Server Components: components themselves run on the server and fetch their own data, writes go through Server Actions, and the framework decides what to prerender and cache. React Router keeps the line between server and browser in two named functions, loader and action, built on web Request, Response and FormData, and leaves caching to HTTP headers you set. Both run as an ordinary Node.js server: Next.js with next start or its standalone output, React Router with react-router-serve. Next.js gives more built in, such as image optimisation and incremental static regeneration, so there is more server behaviour to configure when you host it yourself, especially across several instances. React Router's server does less, so there is less to set up, and you add caching and image handling yourself.

Stop the production server with Ctrl+C. Then remove the project:

Bash
cd ~
rm -rf ~/rr-notes-demo

Check it worked

ls ~/rr-notes-demo reports No such file or directory, and curl http://localhost:3000/ fails to connect. Node.js stays installed.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.