Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 72

Implementing a 404 Catch-All Route

Recommended resources

Hello! Welcome to the final lesson of our module on client-side routing.

In our last lesson, we built a crucial security feature: protected routes. We learned how to control access to specific parts of our application based on a user's authentication status, ensuring that sensitive content like a dashboard is only visible to logged-in users. We handled the case of a valid route that a user isn't authorized to see.

Today, we'll address a different but equally common scenario: what happens when a user tries to navigate to a route that doesn't exist at all? This could be due to a typo in the URL, a bookmarked link that is now outdated, or just simple curiosity. This lesson focuses on the learning outcome: Handle 404 (Not Found) pages using a catch-all route. We will implement a professional and user-friendly "Not Found" page, ensuring users are never left at a dead end.

The Problem: Reaching a Dead End

In a traditional website, requesting a non-existent URL results in a standard "404 Not Found" error from the server. In a React Single Page Application (SPA), React Router is in charge of navigation. If it can't match the current URL to any of its defined routes, the default behavior can be confusing for the user. It might render a blank page, an incomplete layout, or a generic error message like the one below.

404 Not Found Page Example
This is the default error page provided by React Router for an unhandled route error. While functional, it's not ideal for a polished user experience.

A good application should gracefully handle this by showing a custom, helpful "Not Found" page that guides the user back to familiar territory.


The Solution: The "Catch-All" Route

React Router provides an elegant solution for this: the catch-all route, also known as a "splat" route. By defining a route with a special path, *, you can create a component that will render for any URL that has not been matched by the other, more specific routes in your configuration.

The key principle is route ordering. The catch-all route must be the last route in your configuration. React Router attempts to match routes in the order they are defined; if it reaches the * path, it means nothing else has matched.

Let's look at the official documentation to solidify this concept.

Routing

The official React Router documentation explains the concept of 'splats' or catch-all segments. This will give you the foundational knowledge for our implementation.

Read the section titled 'Splats'. Focus on the final two examples, which show how /* can match remaining URL segments and, most importantly, how a standalone * path can be used to create a catch-all route for requests that don't match any other route.

As the documentation shows, a route definition like route("*", "./catchall.tsx") creates the exact behavior we need. Now, let's build the component for it.


Creating a User-Friendly NotFoundPage

A good 404 page does two things:

  1. It clearly informs the user that the page they're looking for doesn't exist.
  2. It provides a clear and easy way to navigate back to a valid part of the application, such as the homepage.

We'll create a new component, NotFoundPage.tsx, to serve this purpose. The following video walks through creating such a component, refactoring inline content into a dedicated page, and adding a <Link> component to guide the user home.

React Router - Complete Tutorial

This video from Cosden Solutions demonstrates how to create a dedicated 'Not Found' page component. Pay close attention to how a simple JSX element is turned into a reusable component and how a <Link> is added to improve the user experience.

Watch from 06:34 to 08:30. This part covers creating the NotFoundPage component and adding a Link back to the homepage. The video also discusses the difference between <Link> and a standard <a> tag, which is a great review of client-side routing principles.

Based on that guide, here’s how we can create our NotFoundPage.tsx file in our TypeScript project.

// src/pages/NotFoundPage.tsx

import { Link } from 'react-router-dom';

const NotFoundPage = () => {
  return (
    <div style={{ textAlign: 'center', marginTop: '50px' }}>
      <h1>404 - Not Found</h1>
      <p>Oops! The page you are looking for does not exist.</p>
      <Link to="/">Go back to the homepage</Link>
    </div>
  );
};

export default NotFoundPage;

This component is simple, but effective. It uses the <Link> component from react-router-dom to ensure navigation happens on the client-side without a full page refresh.


Integrating the Catch-All Route

Now we can add our NotFoundPage to our router configuration. Since you're using createBrowserRouter with an object-based configuration, we'll add a new route object to the array. Remember, it must be the very last one.

Here is an example of a complete RoutesRenderer component from a blog post that showcases this exact pattern.

A Modular Approach to Integrating React-Router v6

This article by Miguel Angel Jerez showcases a modular routing setup. The key takeaway is in the RoutesRenderer component, where you can see the catch-all <Route> being placed after all other routes are mapped.

Focus on the code snippet for the RoutesRenderer component. Notice the line <Route key={'not-found'} path={'*'} element={<NotFoundPage/>}/> at the end of the <Routes> block. This is the pattern we are implementing.

Applying this pattern to our createBrowserRouter configuration in main.tsx would look like this:

// src/main.tsx

import { createBrowserRouter, RouterProvider } from 'react-router-dom';
import HomePage from './pages/HomePage';
import DashboardLayout from './layouts/DashboardLayout';
import LoginPage from './pages/LoginPage';
import ProtectedRoute from './components/ProtectedRoute';
import NotFoundPage from './pages/NotFoundPage'; // 1. Import the component

// ... other imports ...

const router = createBrowserRouter([
  {
    path: '/login',
    element: <LoginPage />,
  },
  {
    element: <ProtectedRoute />, // Using the component from the previous lesson
    children: [
      {
        path: '/', // Changed to be protected for this example
        element: <HomePage />,
      },
      {
        path: '/dashboard',
        element: <DashboardLayout />,
        // ... nested dashboard routes
      },
    ],
  },
  // 2. Add the catch-all route as the LAST element in the array
  {
    path: '*',
    element: <NotFoundPage />,
  },
]);

// ... ReactDOM.render call ...

With this change, any URL that doesn't match /login, /, or /dashboard (or its children) will be caught by the path: '*' route, and our NotFoundPage component will be rendered.

Test your understanding!

You have a nested route structure for a blog: /blog renders a layout component, and /blog/:postId renders a specific post. You want to show a special PostNotFound component for URLs like /blog/some-invalid-id, but a generic NotFoundPage for everything else (like /invalid-top-level-route).

How would you modify your route configuration to achieve this?

Show answer

You would add a catch-all route specifically inside the children array of the /blog route object, in addition to the global catch-all route. The router will first try to match routes inside the nested structure.

const router = createBrowserRouter([
  // ... other top-level routes
  {
    path: '/blog',
    element: <BlogLayout />,
    children: [
      {
        path: ':postId',
        element: <BlogPostPage />,
      },
      // Catch-all specific to the /blog path
      {
        path: '*',
        element: <PostNotFound />,
      },
    ],
  },
  // Global catch-all for any other unmatched route
  {
    path: '*',
    element: <NotFoundPage />,
  },
]);

An Alternative: errorElement

In modern React Router (v6.4+), the object-based configuration introduces another powerful feature: the errorElement property on a route object. While our path="*" solution is perfect for handling 404s, errorElement provides a more comprehensive error-handling mechanism.

React Router - Complete Tutorial

The first video we watched briefly introduced this concept. Let's revisit it to understand this alternative approach.

Watch from 05:44 to 06:34. The presenter demonstrates adding an errorElement to a route. Notice how this element is rendered when the URL doesn't match any defined child path. This provides a single place to handle not-found states and other rendering errors for a whole subtree of routes.

The errorElement will catch errors that happen during rendering or data loading within its route and any of its descendant routes. When React Router fails to find a matching route, it internally throws an error with a 404 status, which errorElement can catch.

You could define it on your root route:

const router = createBrowserRouter([
  {
    path: '/',
    element: <RootLayout />,
    errorElement: <ErrorPage />, // Catches 404s and other errors
    children: [
        // ... all your other routes
    ]
  }
]);

This is a more advanced pattern and is closely related to "Error Boundaries," a topic we will cover in depth in Module 12. For now, using path="*" is the most direct and idiomatic way to solve the specific problem of a 404 page.


Conclusion

Congratulations on completing the module on client-side routing! You now have a complete toolkit for managing navigation in a modern React application, from defining basic routes to handling complex scenarios like nested layouts, protected areas, and now, graceful error handling for non-existent pages.

Key Takeaways:

  • A catch-all route handles URLs that don't match any other defined route, preventing a poor user experience.
  • The path="*" syntax is used to define a catch-all route.
  • This route must be placed last in your list of routes to function correctly.
  • A good "Not Found" page should be user-friendly and provide a <Link> to guide the user back to a valid section of the app.
  • The errorElement property offers a more comprehensive, but different, error-handling strategy that we will revisit later.

Preview of the Next Lesson:
We've spent the last few modules building the "skeleton" of our application—components, composition, and navigation. In the next module, "Advanced State Management," we'll dive into the "brain." We'll start by comparing React's built-in state management tools (useState, useReducer, Context) with powerful external libraries, helping you understand when and why to reach for more advanced solutions.