Course contentsShow
← Web Development
Lesson 983 of 2,98217. URL and History ManagementFree lesson

404 and Fallback Routes

Handle unknown paths gracefully with catch-all routes and error pages.

404 and Fallback Routes

You'll learn how to handle unknown or invalid paths gracefully, ensuring users always see something helpful instead of a broken page.

The Problem with Unmatched Routes

When building client-side routing, users might navigate to URLs that don't exist—whether through typos, outdated bookmarks, or broken links. Without proper handling, these "lost" users would see a blank page or JavaScript errors. A fallback route acts like a safety net, catching any navigation that doesn't match your defined routes.

How Fallback Routes Work

Think of your router as a bouncer at a venue checking a guest list. If someone's name matches, they get directed to the right room. But if their name isn't on the list at all, instead of leaving them confused at the door, the bouncer directs them to a "guest services" area where they can get help.

In routing terms, you define a catch-all pattern that matches when nothing else does. This typically uses a wildcard pattern (like *) checked last in your route matching logic. When your route matcher cycles through all defined routes and finds no match, it falls through to the catch-all route.

const routes = [
  { path: '/', handler: homePage },
  { path: '/about', handler: aboutPage },
  { path: '/contact', handler: contactPage },
  { path: '*', handler: notFoundPage } // Catch-all must be last
];

Your 404 page should be user-friendly: explain what happened, suggest navigation options, and maintain your site's design consistency. It's not an error—it's an opportunity to guide users back to useful content.

Key Takeaway: Always include a fallback route as your last route definition to handle unmatched paths gracefully and provide users with helpful navigation options instead of broken experiences.