Blog>
Snippets

Handling 404 Pages with TanStack Router

Show an example of how to create and manage a custom 404 Not Found page using TanStack Router, improving the user experience for invalid routes.
import { createBrowserRouter, RouterProvider, Route } from 'react-router-dom';
import HomePage from './HomePage';
import NotFoundPage from './NotFoundPage';
First, import the necessary components from TanStack Router. Here, `HomePage` represents the component for the main route, and `NotFoundPage` is our custom 404 page.
const router = createBrowserRouter([
  { path: '/', element: <HomePage /> },
  { path: '*', element: <NotFoundPage /> }
]);
Create a router instance using `createBrowserRouter`. Define routes including a catch-all route (*) that renders the `NotFoundPage` for any undefined paths.
<RouterProvider router={router} />
Finally, use the `RouterProvider` with the created router instance to set up the routing in your application. The `NotFoundPage` will now be displayed for any non-existent routes.