How to handle 404 pages in React Router
Handling 404 pages properly is essential for React applications to provide users with helpful feedback when they navigate to non-existent routes.
As the creator of CoreUI, a widely used open-source UI library, I’ve implemented 404 handling in countless React applications and admin dashboards.
From my 25 years of experience in web development and 11 years with React, the most effective approach is to use a catch-all route with the wildcard path * at the end of your route definitions.
This pattern ensures all unmatched routes display a user-friendly not found page.
Use a catch-all route with path * at the end of your routes to handle unmatched URLs.
import { Routes, Route } from 'react-router-dom'
import Home from './pages/Home'
import About from './pages/About'
import Contact from './pages/Contact'
import NotFound from './pages/NotFound'
function App() {
return (
<Routes>
<Route path='/' element={<Home />} />
<Route path='/about' element={<About />} />
<Route path='/contact' element={<Contact />} />
<Route path='*' element={<NotFound />} />
</Routes>
)
}
// NotFound.js
function NotFound() {
return (
<div className='not-found'>
<h1>404 - Page Not Found</h1>
<p>The page you're looking for doesn't exist.</p>
<Link to='/'>Go back home</Link>
</div>
)
}
The catch-all route with path * must be placed last in your route definitions because React Router matches routes in order and stops at the first match. The wildcard * matches any path that hasn’t been matched by previous routes. Create a dedicated NotFound component that provides clear messaging and navigation options for users. Include links back to main sections of your application to help users find what they’re looking for.
This is the same 404 handling pattern we use in CoreUI React admin templates to provide professional error pages and maintain good user experience. For better SEO and analytics, ensure your 404 component returns a proper HTTP 404 status code when server-side rendering, and consider adding error tracking to monitor frequently accessed invalid routes.



