Sub topic 6
Index routes and the catch-all 404 route
This chapter assumes you can define route objects with createBrowserRouter, and that you know how a parent route renders its children through <Outlet />. Here you will fill the two gaps that nested routes leave behind. The first is what a layout shows at its own URL. The second is what the app shows when no route matches.
The problem: an empty Outlet
Suppose a layout route has the path / and a single child with the path about. At /about, the layout renders and the child fills the <Outlet />. At /, the layout matches but no child does. The layout renders with an empty outlet, so the page shows only the navigation bar.
An index route fixes this. It is a child route that renders in the parent's outlet when the URL matches the parent's path exactly.
Index routes
You mark a route as an index route with index: true. It has no path.
import {
createBrowserRouter,
RouterProvider,
Link,
Outlet,
useLocation,
} from "react-router-dom";
function Layout() {
return (
<div>
<nav>
<Link to="/">Home</Link> <Link to="/about">About</Link>
</nav>
<Outlet />
</div>
);
}
function NotFound() {
const location = useLocation();
return (
<div>
<h1>Page not found</h1>
<p>Nothing lives at {location.pathname}.</p>
<Link to="/">Back to home</Link>
</div>
);
}
const router = createBrowserRouter([
{
path: "/",
element: <Layout />,
children: [
{ index: true, element: <h1
{ path: "about", element: <h1>About</h1> },
{ path: "*", element: <NotFound /> },
],
},
]);
export default function App() {ider router={router} />;
}The { index: true } child shares its par It does not add a path segment of its own. It is the default content of the parent's outlet.
Rules for index routes
- An index route cannot have a
path. Theindex: trueflag takes the place of one. - An index route cannot have
children. It is a leaf by definition. - A parent can have only one index route.
- An index route can have its own
loader,action, anderrorElement, like any other route. This is useful when the default view needs its own data.
Index route versus a child with `path: "/"`
You may be tempted to write { path: "/", element: <Home /> } as a child of the layout. Do not. It is ambiguous, because it has the same full path as its parent. It also makes the intent unclear to readers. index: true states that this is the parent's default content.
What matches what
| URL | Matched routes | Rendered in the outlet |
|---|---|---|
| `/` | layout, index | Home |
| `/about` | layout, `about` | About |
| `/about/` | layout, `about` | About (a trailing slash is ignored) |
| `/pricing` | layout, `*` | NotFound |
Catch-all (splat) routes
A path of "*" is a splat. It matches any remaining URL segments, including none. It is how you build a 404 page that lives inside your app.
The router does not match routes in the order you wrote them. It ranks every route that could match and picks the most specific one. Static segments such as about beat dynamic segments such as :userId. Dynamic segments beat a splat. So { path: "*" } does not swallow /about, even if you list it first. It only wins when nothing more specific matches.
Where to put the splat route
The position in the tree decides what surrounds the 404 page.
- Inside the layout, as a child. The navigation bar stays visible, so the user can recover. This is what the example above does. It is usually the right choice.
- At the top level, as a sibling of the layout. The 404 page renders alone, with no shared navigation. Use this when the 404 page needs a different design.
- Nested under a section. A route such as
{ path: "docs/*" }handles every unknown URL beneath/docs, while the rest of the app keeps its own behavior.
Reading the unmatched part
The splat segment is available in useParams under the key "*".
import { useParams } from "react-router-dom";
function DocsFallback() {
const params = useParams();
const rest = params["*"];
return <p>No docs page named "{rest}".</p>;
}
// Route definition: { path: "docs/*", element: <DocsFallback /> }For the URL /docs/guides/setup, params["*"] is "guides/setup".
What happens without a splat route
In a data router, an unmatched URL is not silently ignored. The router treats it as a 404 error and shows the nearest errorElement. With no errorElement anywhere, it shows a built-in default error page, which is rarely what you want to ship.
This gives you two ways to build a 404 page. The splat route lets you render the 404 inside the layout. A root errorElement catches all routing errors in one place, but it replaces the layout, because the error element takes the place of the failed route's element.
Two different kinds of "not found"
These cases look similar to a user but differ in the code.
- No route matches the URL. A splat route or the router's 404 error handles it. Example:
/pricingwhen no such page exists. - A route matches but the data does not exist. Example:
/users/9999matchesusers/:userId, but the API has no user 9999. The loader should throw aResponsewith status 404, and the route'serrorElementrenders the message. The splat route never sees this URL.
Keep this split in mind when a bad URL shows the wrong screen. A missing page and a missing record are handled in different places.
Common errors
- Adding
pathto an index route.{ index: true, path: "home" }is invalid. If you need a URL, make it a normal child route. - Giving an index route
children. The router rejects it. Move the children to a sibling route with a path. - Forgetting the index route. The layout renders but the page body is blank. Add
{ index: true, element: ... }. - Putting the splat only at the top level and expecting the layout. A top-level
"*"route renders without the layout. If the navigation bar disappears on bad URLs, move the splat inside the layout'schildren. - Assuming the server returns a 404 status. The client router renders a 404 page, but the HTTP response was already sent. Your server serves
index.htmlwith status 200 for every path, so crawlers may index unknown URLs as real pages. If that matters, handle status codes on the server. - Relying on route order. The router ranks by specificity, so reordering the array does not change which route wins. If a route does not match, check the path string, not its position.
Summary of decisions
- Give every layout route an index route, unless a blank outlet is intended.
- Put one
"*"route inside the layout for a friendly 404 with navigation. - Use a loader that throws a 404
Responsefor missing records, and handle it witherrorElement.
Exercise
A layout route at "/" has children { path: "about" } and { path: "*" }, but no index route. What renders in the outlet at the URL "/", and what change makes the home page show a "Welcome" heading?
Show answer
The splat route matches, because "*" also matches zero remaining segments, so the 404 page renders at "/". Add a child { index: true, element: <h1>Welcome</h1> }. The index route is more specific than the splat for the exact parent URL, so it wins.
Exercise
The URL "/users/9999" shows the root error page instead of your 404 splat page. The route is { path: "users/:userId", loader } and the loader throws new Response("Not found", { status: 404 }). Why does the splat route not handle it, and where should the message be displayed?
Show answer
The URL matches users/:userId, so the splat route is never considered. The thrown Response is a loader error, which goes to the nearest errorElement. Add an errorElement to the users route (or its parent) that uses useRouteError and isRouteErrorResponse to show the 404 message.