Catch-All Route
Problem
Users who mistype URLs, follow broken links, or access deleted pages see browser error pages or blank screens. There’s no way to handle 404
s gracefully within the application, leaving users stranded without helpful navigation or error messages.
Solution
Register a wildcard route that matches any unhandled path and renders a custom 404
page with helpful navigation or search. This keeps users in your application with a path forward rather than abandoning them to a browser error.
Example
This example demonstrates setting up a catch-all route that displays a custom 404 page for any unmatched URLs.
// React Router configuration with catch-all route
<Routes>
{/* Define specific routes first */}
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
{/* Catch-all route must be last - matches any unhandled path */}
<Route path="*" element={<NotFound />} />
</Routes>
Benefits
- Handles broken links and typos gracefully with custom error pages.
- Keeps users in the application with helpful navigation instead of browser errors.
- Provides opportunity to suggest relevant content or search functionality.
- Maintains brand experience even when users reach invalid URLs.
- Can track
404
s to identify broken links that need fixing.
Tradeoffs
- Must be defined last in route configuration or it catches everything.
- Doesn’t distinguish between different types of errors or missing resources.
- Can mask routing configuration bugs if legitimate routes don’t match.
- May prevent proper
HTTP 404
status codes if not implemented server-side. - Requires thoughtful design to be helpful rather than just decorative.