Skip to main content

Web frameworks · Intermediate · 26 min

Add pages and navigation to a React app with React Router 8

By Padding · Updated 18 Nov 2026
React Router 8.5.2 · React 19.3 · Vite 8.3 · Node.js 26.13 · Playwright 1.65.1 · checked on node:26

You will turn a Vite React app into a three-page recipe box with React Router 8.5 in data mode, with a shared layout, URL parameters, loaders, an action, pending UI, error boundaries and a search kept in the URL, then prove the back button and deep links with a Playwright script.

On this page

A React app made with Vite starts as one page. As soon as it has a second screen, you need three things the browser gives a normal website for free: an address for every screen, a working back button, and links people can bookmark or send to a friend. React Router provides those inside a single-page app.

React Router 8 can be used in three modes. This tutorial uses data mode: you describe your routes as plain objects, and each route can say what data it needs (a loader), what happens when a form posts to it (an action), and what to show when something goes wrong (an error boundary). The router runs loaders before it shows a page, so components never render half-empty.

You build a small recipe box with three pages: a home page, a searchable list of recipes, and a page for each recipe where cooks can leave notes. The recipe data lives in a module that pauses for a moment on every call, as a slow network would, so you can see the loading states work. At the end, a Playwright script clicks through the built app and checks that the back button, deep links and error pages behave.

If you have not used React with Vite before, start with build a React 19 app with Vite. If you want to see what a router does under the hood, build a client-side router with the History API writes one by hand.

Step 1 · Create the project and install React Router

Scaffold a React and TypeScript app with Vite, then add React Router at an exact version:

Bash
cd ~
npm create vite@9 react-router-demo -- --template react-ts --no-interactive
cd react-router-demo
npm install
npm install react-router@8.5.2

In version 8 everything comes from the single react-router package. The older react-router-dom package was removed, so if you follow an older guide, import from react-router instead, and import RouterProvider from react-router/dom.

The starter page and its styles are not needed. Remove them, and create a folder for the pages and one for the loaders:

Bash
rm src/App.tsx src/App.css
mkdir -p src/pages src/loaders

Check it worked

Bash
npm ls react-router

The output names react-router@8.5.2 under react-router-demo. If npm prints a peer dependency warning about React, check that package.json lists react 19.3 or later: React Router 8 needs React 19.2.7 or newer.

Step 2 · Define the routes and a shared layout

Every page shares a header with the site name and the navigation. In React Router that header is a layout route: a component that renders the parts every page has, plus an <Outlet /> where the current child page appears.

Create the layout and the home page:

Bash
cat > src/pages/Layout.tsx <<'TSX'
import { NavLink, Outlet } from 'react-router'

export default function Layout() {
  return (
    <>
      <header className="site-header">
        <p className="brand">Recipe box</p>
        <nav aria-label="Main">
          <NavLink to="/" end>Home</NavLink>
          <NavLink to="/recipes">Recipes</NavLink>
        </nav>
      </header>
      <main>
        <Outlet />
      </main>
    </>
  )
}
TSX
cat > src/pages/Home.tsx <<'TSX'
import { Link } from 'react-router'

export default function Home() {
  return (
    <section>
      <h1>Recipe box</h1>
      <p>Four dishes from across Africa, with notes from the people who cooked them.</p>
      <p><Link to="/recipes">Browse the recipes</Link></p>
    </section>
  )
}
TSX

<NavLink> is a <Link> that knows when it points at the current page. It then adds an active class and aria-current="page", which screen readers announce as "current page". The end prop on the Home link makes it active only on / itself, not on every address that starts with /.

Now describe the routes. The layout is the parent at /, and the home page is its index route, the child that shows when the address is exactly the parent's path:

Bash
cat > src/router.ts <<'TS'
import { createBrowserRouter } from 'react-router'
import Layout from './pages/Layout'
import Home from './pages/Home'

export const router = createBrowserRouter([
  {
    path: '/',
    Component: Layout,
    children: [{ index: true, Component: Home }],
  },
])
TS
cat > src/main.tsx <<'TSX'
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import { RouterProvider } from 'react-router/dom'
import { router } from './router'
import './index.css'

createRoot(document.getElementById('root')!).render(
  <StrictMode>
    <RouterProvider router={router} />
  </StrictMode>,
)
TSX

The router is created once, outside any component, and handed to <RouterProvider>. Do not create it inside a component or keep it in state: it would be rebuilt on every render and lose its place.

Replace the starter stylesheet with a few plain rules, so the pages are readable:

Bash
cat > src/index.css <<'CSS'
:root {
  font-family: system-ui, sans-serif;
  line-height: 1.5;
  color: #1d1f23;
  background: #ffffff;
}

body {
  margin: 0;
}

.site-header {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 1rem;
  padding: 0.75rem 1rem;
  border-bottom: 1px solid #d9dce1;
}

.brand {
  margin: 0;
  font-weight: 700;
}

.site-header nav {
  display: flex;
  gap: 1rem;
}

.site-header a.active {
  font-weight: 700;
  text-decoration: none;
}

.progress {
  margin: 0 0 0 auto;
  min-height: 1.5em;
  color: #6a707b;
}

main {
  max-width: 40rem;
  margin: 0 auto;
  padding: 1rem;
  transition: opacity 0.2s;
}

main.busy {
  opacity: 0.6;
}

.recipe-list,
.notes {
  padding-left: 1.25rem;
}

.search,
.note-form {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
  align-items: center;
}

.note-form {
  flex-direction: column;
  align-items: stretch;
  max-width: 28rem;
}

.note-form button {
  align-self: flex-start;
}

[role='alert'] {
  color: #a1260d;
  margin: 0;
}
CSS

Check the types, then start the dev server. It keeps running, so open a second terminal in ~/react-router-demo for the commands that follow:

Bash
npx tsc -b
Bash
npm run dev

Check it worked

npx tsc -b prints nothing. Open http://localhost:5173/ and you see the header with two links and the Recipe box heading. Home is bold, because it is the active link. The Recipes link leads to a plain "404 Not Found" error screen for now, because that route does not exist yet.

Ask the dev server for an address that has no file behind it:

Bash
curl -s http://localhost:5173/recipes/anything | grep 'id="root"'

It returns the same HTML page as /, with its empty <div id="root"></div>. Vite answers every page address with index.html, and React Router reads the address in the browser and decides what to draw. Remember this for later: your production host must do the same.

Step 3 · Load the recipe list with a loader

Create the data module. It holds four recipes in memory and pauses on every call, as a request over a slow mobile connection would. The search ignores accents, so someone typing on a phone keyboard can find "Thiéboudienne" by typing "thieb":

Bash
cat > src/data.ts <<'TS'
export type Recipe = {
  id: string
  name: string
  region: string
  minutes: number
  summary: string
  notes: string[]
}

const recipes: Recipe[] = [
  {
    id: 'jollof-rice',
    name: 'Jollof rice',
    region: 'West Africa',
    minutes: 75,
    summary: 'Rice cooked in a tomato and pepper base until the bottom turns smoky.',
    notes: [],
  },
  {
    id: 'thieboudienne',
    name: 'Thiéboudienne',
    region: 'Senegal',
    minutes: 120,
    summary: 'Fish, rice and vegetables cooked in one pot with tamarind and herbs.',
    notes: [],
  },
  {
    id: 'ugali-and-sukuma',
    name: 'Ugali and sukuma wiki',
    region: 'East Africa',
    minutes: 30,
    summary: 'Firm maize porridge served with braised collard greens.',
    notes: [],
  },
  {
    id: 'shakshuka',
    name: 'Shakshuka',
    region: 'North Africa',
    minutes: 35,
    summary: 'Eggs poached in a spiced tomato and pepper sauce.',
    notes: [],
  },
]

// Pretend every call crosses a slow network, so pending UI is visible.
const pause = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))

// Lower-case and strip accents, so "thieb" finds "Thiéboudienne".
function fold(text: string) {
  return text.normalize('NFD').replace(/\p{M}/gu, '').toLocaleLowerCase()
}

export async function getRecipes(query = '') {
  await pause(400)
  const q = fold(query.trim())
  return recipes
    .filter((recipe) => fold(recipe.name).includes(q))
    .map((recipe) => structuredClone(recipe))
}

export async function getRecipe(id: string) {
  await pause(400)
  const recipe = recipes.find((item) => item.id === id)
  return recipe ? structuredClone(recipe) : null
}

export async function addNote(id: string, text: string) {
  await pause(800)
  const recipe = recipes.find((item) => item.id === id)
  if (!recipe) throw new Error(`No recipe with the id ${id}`)
  recipe.notes.push(text)
}
TS

In a real app these functions would call your API with fetch. Everything else in this tutorial stays the same when they do.

A loader is a function the router calls before it shows a route. It receives the request, whose URL includes the query string. This one reads an optional q search term, which the search box uses in a later step:

Bash
cat > src/loaders/recipes.ts <<'TS'
import type { LoaderFunctionArgs } from 'react-router'
import { getRecipes } from '../data'

export async function recipesLoader({ request }: LoaderFunctionArgs) {
  const q = new URL(request.url).searchParams.get('q') ?? ''
  return { recipes: await getRecipes(q) }
}
TS
cat > src/pages/Recipes.tsx <<'TSX'
import { Link, useLoaderData } from 'react-router'
import type { recipesLoader } from '../loaders/recipes'

export default function Recipes() {
  const { recipes } = useLoaderData<typeof recipesLoader>()

  return (
    <section>
      <h1>Recipes</h1>
      <ul className="recipe-list">
        {recipes.map((recipe) => (
          <li key={recipe.id}>
            <Link to={`/recipes/${recipe.id}`}>{recipe.name}</Link>{' '}
            <span>{recipe.region} · {recipe.minutes} min</span>
          </li>
        ))}
      </ul>
    </section>
  )
}
TSX

useLoaderData<typeof recipesLoader>() returns whatever the loader returned, typed from the loader itself, so recipe.name is checked by TypeScript. The loaders live in their own files because Vite's fast refresh, and the template's linter, expect component files to export only components.

Add the route. recipes is a path-only parent with no component: it groups the list (its index route) and, in the next step, the recipe pages under one prefix:

Bash
cat > src/pages/AppLoading.tsx <<'TSX'
export default function AppLoading() {
  return <p>Loading the recipe box…</p>
}
TSX
cat > src/router.ts <<'TS'
import { createBrowserRouter } from 'react-router'
import { recipesLoader } from './loaders/recipes'
import Layout from './pages/Layout'
import Home from './pages/Home'
import Recipes from './pages/Recipes'
import AppLoading from './pages/AppLoading'

export const router = createBrowserRouter([
  {
    path: '/',
    Component: Layout,
    HydrateFallback: AppLoading,
    children: [
      { index: true, Component: Home },
      {
        path: 'recipes',
        children: [{ index: true, Component: Recipes, loader: recipesLoader }],
      },
    ],
  },
])
TS
Bash
npx tsc -b

HydrateFallback is what the router shows while the loaders for the very first page are still running. Without it the screen stays blank until the data arrives, which on a slow connection looks like a broken site.

Check it worked

npx tsc -b prints nothing. In the browser, click Recipes. The list of four dishes appears after a short pause, and the Recipes link turns bold. Open the developer tools' Network panel and click between Home and Recipes: no new HTML document is requested, because the router swaps the page in place. Reload on /recipes and you see "Loading the recipe box…" for a moment before the list.

Step 4 · Read the URL parameter on a recipe page

A path segment that starts with a colon is a dynamic segment. For /recipes/jollof-rice, the route :recipeId matches and the loader receives params.recipeId set to jollof-rice. When no recipe has that ID, the loader throws a 404 response with data(), which the router treats as an error rather than as page data:

Bash
cat > src/loaders/recipe.ts <<'TS'
import { data } from 'react-router'
import type { LoaderFunctionArgs } from 'react-router'
import { getRecipe } from '../data'

export async function recipeLoader({ params }: LoaderFunctionArgs) {
  const recipe = await getRecipe(params.recipeId ?? '')
  if (!recipe) {
    throw data(`There is no recipe called "${params.recipeId}".`, { status: 404 })
  }
  return { recipe }
}
TS
cat > src/pages/Recipe.tsx <<'TSX'
import { Link, useLoaderData } from 'react-router'
import type { recipeLoader } from '../loaders/recipe'

export default function Recipe() {
  const { recipe } = useLoaderData<typeof recipeLoader>()

  return (
    <article>
      <p><Link to="/recipes">All recipes</Link></p>
      <h1>{recipe.name}</h1>
      <p>{recipe.region} · {recipe.minutes} minutes</p>
      <p>{recipe.summary}</p>
    </article>
  )
}
TSX
cat > src/router.ts <<'TS'
import { createBrowserRouter } from 'react-router'
import { recipesLoader } from './loaders/recipes'
import { recipeLoader } from './loaders/recipe'
import Layout from './pages/Layout'
import Home from './pages/Home'
import Recipes from './pages/Recipes'
import Recipe from './pages/Recipe'
import AppLoading from './pages/AppLoading'

export const router = createBrowserRouter([
  {
    path: '/',
    Component: Layout,
    HydrateFallback: AppLoading,
    children: [
      { index: true, Component: Home },
      {
        path: 'recipes',
        children: [
          { index: true, Component: Recipes, loader: recipesLoader },
          { path: ':recipeId', Component: Recipe, loader: recipeLoader },
        ],
      },
    ],
  },
])
TS
npx tsc -b

Because the loader throws when there is no recipe, the component only ever runs with a real one, and TypeScript knows recipe is never null inside it.

Check it worked

Click any dish in the list. The address changes to something like /recipes/shakshuka and the recipe's name, region and summary appear. Press the browser's back button and you are on the list again. Copy the recipe address into a new tab: the same recipe opens directly. Now visit /recipes/pounded-yam. You get the router's built-in error screen with a 404, and the header disappears. The next two steps replace that screen.

Step 5 · Save notes with an action and show pending UI

An action handles a form submission to its route. React Router's <Form method="post"> sends the form's fields to the action of the route it sits in, without a page reload. When the action finishes, the router runs the page's loaders again, so the new note appears without any code to refresh the data.

The action checks the input and returns an error message instead of saving an empty note:

Bash
cat > src/loaders/recipe.ts <<'TS'
import { data } from 'react-router'
import type { ActionFunctionArgs, LoaderFunctionArgs } from 'react-router'
import { addNote, getRecipe } from '../data'

export async function recipeLoader({ params }: LoaderFunctionArgs) {
  const recipe = await getRecipe(params.recipeId ?? '')
  if (!recipe) {
    throw data(`There is no recipe called "${params.recipeId}".`, { status: 404 })
  }
  return { recipe }
}

export async function addNoteAction({ params, request }: ActionFunctionArgs) {
  const form = await request.formData()
  const note = String(form.get('note') ?? '').trim()
  if (note === '') {
    return { error: 'Write a note before saving.' }
  }
  await addNote(params.recipeId ?? '', note)
  return { error: null }
}
TS

Now the page. useActionData returns what the action last returned, which is where the error message comes from. useNavigation describes any navigation in progress: its formData is set from the moment a form is submitted until the reloaded data arrives, which is exactly when the button should say "Saving…":

Bash
cat > src/pages/Recipe.tsx <<'TSX'
import { Form, Link, useActionData, useLoaderData, useNavigation } from 'react-router'
import type { addNoteAction, recipeLoader } from '../loaders/recipe'

export default function Recipe() {
  const { recipe } = useLoaderData<typeof recipeLoader>()
  const result = useActionData<typeof addNoteAction>()
  const navigation = useNavigation()
  const saving = navigation.formData !== undefined

  return (
    <article>
      <p><Link to="/recipes">All recipes</Link></p>
      <h1>{recipe.name}</h1>
      <p>{recipe.region} · {recipe.minutes} minutes</p>
      <p>{recipe.summary}</p>

      <h2>Cooks’ notes</h2>
      {recipe.notes.length === 0 ? (
        <p>No notes yet.</p>
      ) : (
        <ul className="notes">
          {recipe.notes.map((note, index) => (
            <li key={index}>{note}</li>
          ))}
        </ul>
      )}

      <Form method="post" key={recipe.notes.length} className="note-form">
        <label htmlFor="note">Your note</label>
        <textarea
          id="note"
          name="note"
          rows={3}
          aria-describedby={result?.error ? 'note-error' : undefined}
        />
        {result?.error && <p id="note-error" role="alert">{result.error}</p>}
        <button type="submit" disabled={saving}>
          {saving ? 'Saving…' : 'Save note'}
        </button>
      </Form>
    </article>
  )
}
TSX

Four details do quiet work here:

  • The form posts to the page it is on, so React Router replaces the current history entry instead of adding one. After saving a note, Back takes the reader to the list, not to the same recipe a second time. You only need the replace prop when a form posts to a different address; replace={false} turns the default off.
  • aria-describedby points at the error message only while there is one, so the text box never refers to an id that is not on the page.
  • key={recipe.notes.length} gives the form a new identity when a note is added. React then draws a fresh, empty form, which clears the text box without an effect.
  • The text box has no required attribute on purpose, so you can watch the action's own check work. In a real app keep both: the browser check is quicker, and the action check cannot be skipped.

Show the same kind of feedback for page changes. Update the layout so a status line says "Loading…" and the page fades while the next page's loader runs:

Bash
cat > src/pages/Layout.tsx <<'TSX'
import { NavLink, Outlet, useNavigation } from 'react-router'

export default function Layout() {
  const navigation = useNavigation()
  const busy = navigation.state !== 'idle'

  return (
    <>
      <header className="site-header">
        <p className="brand">Recipe box</p>
        <nav aria-label="Main">
          <NavLink to="/" end>Home</NavLink>
          <NavLink to="/recipes">Recipes</NavLink>
        </nav>
        <p className="progress" role="status">{busy ? 'Loading…' : ''}</p>
      </header>
      <main className={busy ? 'busy' : undefined}>
        <Outlet />
      </main>
    </>
  )
}
TSX

navigation.state is idle when nothing is happening, loading while loaders run, and submitting while an action runs. The status line uses role="status", so screen readers announce "Loading…" without moving focus.

Register the action on the recipe route:

Bash
cat > src/router.ts <<'TS'
import { createBrowserRouter } from 'react-router'
import { recipesLoader } from './loaders/recipes'
import { addNoteAction, recipeLoader } from './loaders/recipe'
import Layout from './pages/Layout'
import Home from './pages/Home'
import Recipes from './pages/Recipes'
import Recipe from './pages/Recipe'
import AppLoading from './pages/AppLoading'

export const router = createBrowserRouter([
  {
    path: '/',
    Component: Layout,
    HydrateFallback: AppLoading,
    children: [
      { index: true, Component: Home },
      {
        path: 'recipes',
        children: [
          { index: true, Component: Recipes, loader: recipesLoader },
          {
            path: ':recipeId',
            Component: Recipe,
            loader: recipeLoader,
            action: addNoteAction,
          },
        ],
      },
    ],
  },
])
TS
npx tsc -b

React Router 8 also ships an experimental unstable_useRouterState hook that may one day replace useNavigation and useSearchParams. Stick to the stable hooks until it loses the unstable_ prefix.

Check it worked

Open a recipe and press Save note with the box empty: "Write a note before saving." appears in red under the box. Type a note and save. The button reads "Saving…" and is disabled for about a second, then the note appears under Cooks' notes and the box is empty again. Click between pages and watch "Loading…" appear at the right of the header while each loader runs.

The notes live in the page's memory, so a full reload clears them. In a real app, addNote would send the note to your API.

Step 6 · Catch missing records with error boundaries

An error boundary is a component the router shows in place of a route when that route's loader, action or component fails. The router uses the nearest boundary above the failure, so where you put boundaries decides how much of the screen an error replaces.

Add two. The one on the recipe route handles a missing recipe and keeps the header on screen, because it renders inside the layout's outlet. The one on the root route is the last resort, and also catches addresses that match no route at all:

Bash
cat > src/pages/Errors.tsx <<'TSX'
import { Link, isRouteErrorResponse, useRouteError } from 'react-router'

export function RecipeError() {
  const error = useRouteError()
  const notFound = isRouteErrorResponse(error) && error.status === 404

  return (
    <section>
      <h1>{notFound ? 'Recipe not found' : 'This recipe failed to load'}</h1>
      <p>{notFound ? String(error.data) : 'Try again in a moment.'}</p>
      <p><Link to="/recipes">See all recipes</Link></p>
    </section>
  )
}

export function RootError() {
  const error = useRouteError()
  const notFound = isRouteErrorResponse(error) && error.status === 404
  if (!notFound) console.error(error)

  return (
    <main>
      <h1>{notFound ? 'Page not found' : 'Something went wrong'}</h1>
      <p>{notFound ? 'There is no page at this address.' : 'Reload the page, or try again later.'}</p>
      <p><Link to="/">Go to the home page</Link></p>
    </main>
  )
}
TSX

useRouteError returns whatever was thrown. isRouteErrorResponse is true for responses thrown on purpose, like the loader's data(..., { status: 404 }), and then error.status and error.data hold the status and message. Anything else is a bug, so the root boundary logs it to the console and shows a general message rather than the error's text.

Attach them to the routes:

Bash
cat > src/router.ts <<'TS'
import { createBrowserRouter } from 'react-router'
import { recipesLoader } from './loaders/recipes'
import { addNoteAction, recipeLoader } from './loaders/recipe'
import Layout from './pages/Layout'
import Home from './pages/Home'
import Recipes from './pages/Recipes'
import Recipe from './pages/Recipe'
import { RecipeError, RootError } from './pages/Errors'
import AppLoading from './pages/AppLoading'

export const router = createBrowserRouter([
  {
    path: '/',
    Component: Layout,
    ErrorBoundary: RootError,
    HydrateFallback: AppLoading,
    children: [
      { index: true, Component: Home },
      {
        path: 'recipes',
        children: [
          { index: true, Component: Recipes, loader: recipesLoader },
          {
            path: ':recipeId',
            Component: Recipe,
            loader: recipeLoader,
            action: addNoteAction,
            ErrorBoundary: RecipeError,
          },
        ],
      },
    ],
  },
])
TS
npx tsc -b

Check it worked

Visit /recipes/pounded-yam. The header and navigation stay, and the page says "Recipe not found" and "There is no recipe called "pounded-yam".", with a link back to the list. Now visit /no-such-page. That address matches no route, so the root boundary replaces the whole screen with "Page not found" and a link to the home page.

Step 7 · Keep the search in the URL with useSearchParams

A search box that keeps its term only in component state forgets it on reload and cannot be shared. Put the term in the query string instead: /recipes?q=jollof is then a link anyone can open, and Back returns to the previous search.

useSearchParams reads and writes the query string. Calling setSearchParams is a navigation like clicking a link, so the router runs the list's loader again, and the loader you wrote earlier already filters by q:

Bash
cat > src/pages/Recipes.tsx <<'TSX'
import type { FormEvent } from 'react'
import { Link, useLoaderData, useSearchParams } from 'react-router'
import type { recipesLoader } from '../loaders/recipes'

export default function Recipes() {
  const { recipes } = useLoaderData<typeof recipesLoader>()
  const [searchParams, setSearchParams] = useSearchParams()
  const q = searchParams.get('q') ?? ''

  function search(event: FormEvent<HTMLFormElement>) {
    event.preventDefault()
    const value = String(new FormData(event.currentTarget).get('q') ?? '').trim()
    setSearchParams(value ? { q: value } : {})
  }

  return (
    <section>
      <h1>Recipes</h1>
      <form role="search" className="search" onSubmit={search}>
        <label htmlFor="q">Search by name</label>
        <input id="q" name="q" type="search" defaultValue={q} key={q} />
        <button type="submit">Search</button>
        {q && (
          <button type="button" onClick={() => setSearchParams({})}>
            Clear
          </button>
        )}
      </form>
      {q && <p>Matches for “{q}”: {recipes.length}</p>}
      <ul className="recipe-list">
        {recipes.map((recipe) => (
          <li key={recipe.id}>
            <Link to={`/recipes/${recipe.id}`}>{recipe.name}</Link>{' '}
            <span>{recipe.region} · {recipe.minutes} min</span>
          </li>
        ))}
      </ul>
    </section>
  )
}
TSX
npx tsc -b

The input takes its starting value from the URL with defaultValue. The key={q} matters for the back button: when Back changes the URL from ?q=thieb to no search, the key changes, React draws a new input, and the box shows the term that belongs to that history entry instead of whatever was last typed.

Check it worked

On the Recipes page, type thieb and press Search. The address becomes /recipes?q=thieb, the line "Matches for "thieb": 1" appears, and only Thiéboudienne is listed. Search for jollof, then press Back: the box and the list return to thieb. Press Clear and all four dishes return. Paste http://localhost:5173/recipes?q=ugali into a new tab, and the search is already filled in.

Step 8 · Build the app and test it in a real browser

Stop the dev server with Ctrl+C in its terminal, then build the app for production:

Bash
npm run build

Serve the build in your second terminal and leave it running:

Bash
npm run preview

Install Playwright and its copy of Chromium. On Linux, --with-deps also installs the system libraries Chromium needs and may ask for your sudo password:

Bash
npm install --save-dev playwright@1.65.1
npx playwright install --with-deps chromium

The script below drives the built app the way a person would. It sets a marker on window at the start and checks it is still there after several clicks and two presses of Back, which proves the browser never loaded a new document. Then it opens addresses directly, as a bookmark would:

Bash
cat > e2e.mjs <<'JS'
import { chromium } from 'playwright'
import assert from 'node:assert/strict'

const site = 'http://localhost:4173'
const browser = await chromium.launch()
const page = await browser.newPage()

const rows = page.locator('.recipe-list li')
const waitForRows = (n) =>
  page.waitForFunction((count) => document.querySelectorAll('.recipe-list li').length === count, n)

try {
  // 1. Links change the page without a full reload.
  await page.goto(`${site}/`)
  await page.getByRole('heading', { name: 'Recipe box', exact: true }).waitFor()
  await page.evaluate(() => { window.sameDocument = true })
  await page.getByRole('navigation').getByRole('link', { name: 'Recipes' }).click()
  await page.waitForURL(`${site}/recipes`)
  await waitForRows(4)
  const recipesLink = page.getByRole('navigation').getByRole('link', { name: 'Recipes' })
  assert.equal(await recipesLink.getAttribute('aria-current'), 'page')
  console.log('ok: links navigate on the client, active link marked')

  // 2. The search term goes into the URL; accents are ignored.
  await page.getByLabel('Search by name').fill('thieb')
  await page.getByRole('button', { name: 'Search' }).click()
  await page.waitForURL(`${site}/recipes?q=thieb`)
  await waitForRows(1)
  assert.equal(await rows.first().getByRole('link').textContent(), 'Thiéboudienne')
  console.log('ok: search updates the URL and the list')

  // 3. A dynamic segment opens the detail page.
  await page.getByRole('link', { name: 'Thiéboudienne' }).click()
  await page.waitForURL(`${site}/recipes/thieboudienne`)
  await page.getByRole('heading', { name: 'Thiéboudienne', level: 1 }).waitFor()
  console.log('ok: detail page loads from the URL parameter')

  // 4. The action validates, shows pending UI and saves.
  await page.getByRole('button', { name: 'Save note' }).click()
  await page.getByRole('alert').filter({ hasText: 'Write a note before saving.' }).waitFor()
  await page.getByLabel('Your note').fill('Ask the fishmonger for thiof.')
  await page.getByRole('button', { name: 'Save note' }).click()
  await page.getByRole('button', { name: 'Saving…' }).waitFor()
  await page.locator('.notes li', { hasText: 'Ask the fishmonger for thiof.' }).waitFor()
  assert.equal(await page.getByLabel('Your note').inputValue(), '')
  console.log('ok: action validates, shows Saving… and adds the note')

  // 5. The back button returns to the search, then the full list.
  await page.goBack()
  await page.waitForURL(`${site}/recipes?q=thieb`)
  await waitForRows(1)
  assert.equal(await page.getByLabel('Search by name').inputValue(), 'thieb')
  await page.goBack()
  await page.waitForURL(`${site}/recipes`)
  await waitForRows(4)
  assert.equal(await page.evaluate(() => window.sameDocument), true)
  console.log('ok: back button walks the history without reloading')

  // 6. Deep links work on a fresh load.
  await page.goto(`${site}/recipes?q=jollof`)
  await waitForRows(1)
  assert.equal(await page.getByLabel('Search by name').inputValue(), 'jollof')
  await page.goto(`${site}/recipes/ugali-and-sukuma`)
  await page.getByRole('heading', { name: 'Ugali and sukuma wiki', level: 1 }).waitFor()
  console.log('ok: deep links load the right page')

  // 7. Missing records and unknown addresses show error pages.
  await page.goto(`${site}/recipes/pounded-yam`)
  await page.getByRole('heading', { name: 'Recipe not found' }).waitFor()
  assert.ok(await page.getByRole('navigation').isVisible(), 'the layout stays on screen')
  await page.goto(`${site}/no-such-page`)
  await page.getByRole('heading', { name: 'Page not found' }).waitFor()
  console.log('ok: error boundaries handle a missing recipe and an unknown page')

  console.log('All checks passed')
} finally {
  await browser.close()
}
JS
node e2e.mjs

Check it worked

The script prints seven ok: lines and ends with All checks passed. If a check fails, Playwright names the locator it was waiting for, and the step number in the comments tells you which page to open by hand.

The preview server, like the dev server, answers every address with index.html. Your production host must do the same, or a deep link such as /recipes/shakshuka returns the host's own 404 page. On Nginx, the line inside the site's location / block is:

Nginx
try_files $uri $uri/ /index.html;

Most static hosts have a similar single-page app or rewrite setting.

When you are finished, stop the preview server with Ctrl+C and remove the demo project. The Chromium that Playwright downloaded stays in its shared cache. If you no longer need it, run npx playwright uninstall inside the project before you delete it, because the command uses the project's copy of Playwright.

Bash
cd ~
rm -rf ~/react-router-demo

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.