Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 50 ยท Declarative Routing Basics

404 Pages and Catch-All Routes

Build a 404 page with a path=* route, read splat params, put a not-found inside a layout, and learn why single-page apps need extra work to send a real 404 status.

Sooner or later someone types a URL your app does not know: a typo, an old bookmark, a link from a site you do not control. If your router has no answer, the user sees an empty page and no explanation. A good app always has a fallback that says "this page does not exist" and shows a way back.

React Router handles this with a catch-all route: a route whose path is *. It matches any URL that nothing else matched, and it ranks below every other route, so it never steals a URL from a real page. In this lesson you will add a 404 page, learn how the * part of a path (a splat) becomes a value you can read, place a not-found page inside a layout, and see why the HTTP status code of a 404 is a separate problem in single-page apps. If you have not yet seen how matching works, read Routes and Matching first.

A catch-all route

Here is the real React Router code (read-only, because the live editor cannot install packages):

JSX
// App.jsx - React Router (read-only)
import { Routes, Route } from 'react-router';

export default function App() {
  return (
    <Routes>
      <Route path="/" element={<Home />} />
      <Route path="about" element={<About />} />
      <Route path="products" element={<Products />} />
      <Route path="*" element={<NotFound />} />
    </Routes>
  );
}

Nothing special is needed to make * "last": React Router scores every route by how specific its pattern is and picks the best match, so a static segment such as about always beats *, wherever you write it. Putting the catch-all at the end is still a good habit, because it reads like a default branch.

Real library or stand-in? The code above is the real API. The live examples in this lesson use a small hand-written router built on React and location.hash (hash routing works inside the sandboxed preview). It has the same shape: a list of routes, a matcher, Link-style anchors. Unlike the real router, it simply uses the first route that matches, so in the stand-in the order of the list matters and * has to come last. The core of the stand-in is explained in Client-Side Routing.

A catch-all 404 route

Click "Old pricing link": no pattern matches /pricing/enterprise, so the * route renders and the page can even show the URL that failed. A useful 404 page repeats the bad address, offers a link home (or a search box) and keeps the site navigation visible so the visitor is not stranded.

Splat routes: the star as a value

A * can also end a longer pattern. docs/* matches /docs, /docs/intro and /docs/guides/setup/linux. The part that the star swallowed is stored in the params object under the key "*":

JSX
// DocsPage.jsx - React Router (read-only)
import { useParams } from 'react-router';

export default function DocsPage() {
  const { '*': rest } = useParams();
  // URL /docs/guides/setup  ->  rest === "guides/setup"
  return <p>You asked for: {rest}</p>;
}

Splat routes are the right tool when a whole subtree of URLs is handled by one component, for example a file browser, a documentation viewer or a section that renders its own inner router. The rules to remember:

  • The * must be the last segment of the path. Patterns such as docs/*/edit or file* are not supported.
  • The value is the raw remainder, without a leading slash. It is empty when the URL is just /docs.
  • A splat route is the lowest-ranked kind of route, which is exactly why a plain path="*" works as a catch-all.
  • The splat value is a string that came from outside. Treat it like any other URL param: validate it before using it to fetch a file or build a query.

Not-found inside a layout

A top-level * route replaces the whole screen, header and all. Often you want the opposite: the header and sidebar stay, and only the content area says "not found". For that, put a * route inside a layout route. A nested * only catches URLs that live under its parent, so you can have a different message for each section of the site.

JSX
// App.jsx - React Router (read-only)
<Routes>
  <Route path="/" element={<SiteLayout />}>
    <Route index element={<Home />} />
    <Route path="docs/*" element={<DocsViewer />} />
    <Route path="shop" element={<ShopLayout />}>
      <Route index element={<ShopHome />} />
      <Route path="item/:id" element={<Item />} />
      <Route path="*" element={<ShopNotFound />} />
    </Route>
    <Route path="*" element={<NotFound />} />
  </Route>
</Routes>

With this tree, /shop/gizmos is caught by ShopNotFound, which renders inside ShopLayout, which renders inside SiteLayout. /blog is caught by the outer NotFound, which still sits inside SiteLayout. Nesting and the Outlet component are explained properly in Nested Routes and Outlet; here you only need the picture:

flowchart TD
    A["URL: /shop/gizmos"] --> B["SiteLayout (header, footer)"]
    B --> C["ShopLayout (shop tabs)"]
    C --> D["path='*' matches<br/>ShopNotFound"]
    E["URL: /blog"] --> F["SiteLayout (header, footer)"]
    F --> G["path='*' matches<br/>NotFound"]

The same layouts wrap both 404s. The nearer the not-found route is to the broken URL, the more of the page survives.

Splat values and a not-found inside a layout

Open "Docs" and read the splat value: it is guides/setup, the part after docs/. Then compare the two bad links. "Bad shop URL" keeps the "Shop" heading because the not-found route is a child of ShopLayout, while "Bad site URL" loses it but keeps the top navigation.

The status code problem

Everything above changes what the user sees. It does not change what the server answers. This matters because search engines read the HTTP status code, not your headline.

In a classic single-page app, the browser requests /pricing/enterprise, the host has no such file, and (to make client-side routing work at all) it is configured to answer every unknown path with index.html and status 200 OK. React then loads, your catch-all route renders "Page not found", but the response was a success. Crawlers see a 200 page with thin content: a soft 404. Options for a client-only app:

  • Add <meta name="robots" content="noindex"> while the not-found view is shown, so it is not indexed.
  • Have the server (or CDN) answer 404 for URL shapes that can never exist, and for known dynamic URLs check whether the record exists.
  • Move to server rendering, where the router runs on the server and can choose the status.

With server rendering (React Router framework mode, or a data-mode router rendered by your own server) a route's loader can throw a response, and the server uses its status:

JSX
// product.jsx - React Router (read-only)
import { data } from 'react-router';

export async function loader({ params }) {
  const product = await findProduct(params.id);
  if (!product) {
    throw data('Product not found', { status: 404 });
  }
  return product;
}

Note that a route which merely matches (even *) counts as a successful match, so on a server the catch-all route should throw a 404 response from its loader too. Error boundaries for those thrown responses are the topic of Error Boundaries and Error Elements.

The interactive example below simulates what a server would answer for a few URLs, using the same idea as before: the pattern decides which page renders, but a separate "does the record exist" check decides the status.

What status would the server send?

The row for /products/99 is the subtle one: the route pattern matched, the page shows "not found", and only the extra check turns the status into 404. A client-only app cannot do that check before the page is sent, which is why server rendering is the complete fix.

Good 404 pages

  • Say plainly that the page does not exist, and echo the address.
  • Keep the site header so users can navigate on.
  • Offer a next step: a link to the home page, a popular section or a search form.
  • Set the document title (for example "Page not found") so the browser tab and history make sense.
  • Use a nested not-found for sections with dynamic content, so users keep their context.
  • Do not redirect every unknown URL to the home page: users and crawlers cannot tell that the original address was wrong.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which route catches every URL that no other route matched?

    A path of * is a splat that matches any remaining URL. It ranks lowest, so real routes always win. A route at /404 only matches that exact address, and index or empty paths match the parent's own URL.
  2. 2. A route has the path docs/* and the URL is /docs/guides/setup. How do you read the part the star matched?

    The remainder is stored in the params object under the key '*', as one string without a leading slash.
  3. 3. You want the site header to stay visible when someone opens a bad URL under /shop. Where should the not-found route go?

    A nested * route only catches URLs under its parent and renders in the parent's Outlet, so the parent layouts around it stay on screen.
  4. 4. Your client-only app shows a 'Page not found' screen for /old-page. What does a search engine usually see?

    The status code comes from the server's HTTP response, not from what React renders. A host that falls back to index.html answers 200. Server rendering (or server rules and noindex) is needed to fix it.

Summary

  • A path="*" route is the fallback for unmatched URLs and is ranked below every more specific route.
  • A * at the end of a longer path (docs/*) is a splat; read the matched remainder with useParams()['*'].
  • Put a * route inside a layout to keep headers and sidebars, and use different not-found routes for different sections.
  • Rendering a 404 page does not send a 404 status: client-only apps produce soft 404s, while server rendering lets loaders throw a response with status: 404.
  • A good 404 page names the problem, keeps navigation and offers a way forward.

Next: Routes as Objects: useRoutes and Route Configs