Handle Unknown Routes

What happens if the user navigates to a URL that does not exist? Right now nothing in our app handles that, so the user does not get a 404 page. We can fix that by defining a notFoundComponent in our root route.

The NotFound component

Update src/routes/__root.tsx:

import { createRootRoute, Link, Outlet } from "@tanstack/react-router";

export const Route = createRootRoute({
  component: RootLayout,
  notFoundComponent: NotFound, // ๐Ÿ‘€
});

function RootLayout() {
  // Same as before, with navigation links and <Outlet />
}

// ๐Ÿ‘€ This component renders when no route matches the URL
function NotFound() {
  return (
    <div className="flex min-h-[50vh] flex-col items-center justify-center gap-4">
      <h1 className="text-4xl font-bold">404</h1>
      <p className="text-muted-foreground">Page not found.</p>
      <Link to="/" className="text-primary underline">
        Go back home
      </Link>
    </div>
  );
}

The notFoundComponent is what renders when no route matches the URL. So for any URL we did not define a route for, the user sees this 404 page and a link back to the home page.

Test it out

Run the dev server and try navigating to a URL that does not exist (e.g., /kudoboard/nonexistent). It should show the 404 page.

404 page for unknown routes

Checkpoint: Commit your progress.

git add .
git commit -m "kudoboard-03: Add notFoundComponent for unknown routes"
git push