How To Handle 404 Error in React JS

Udemezue John - Oct 6 - - Dev Community

Introduction.

Handling 404 errors in a React application can be tricky, but it's an essential aspect of building a reliable user experience. Whether you're working on a single-page application (SPA) or a traditional multi-page site, users may sometimes land on pages that don’t exist—either because of a typo in the URL, outdated links, or incorrect routing. If not handled properly, this could lead to user frustration and a poor experience.

In React, managing these 404 errors—essentially telling the user, "Hey, this page doesn’t exist, but here's what you can do next"—is more than just displaying a "Page Not Found" message.

It involves implementing proper routing logic and delivering a user-friendly interface that seamlessly guides users back to the right place.

I'll explore practical ways to handle 404 errors in React, ensuring both the functionality and aesthetics of your app are intact.

What Exactly Is a 404 Error?

Before jumping into the implementation, it’s important to know what a 404 error is.

A 404 error means that the server could not find the resource (page, file, etc.) requested by the client (in this case, the browser).

In the context of React, this typically happens when a user tries to visit a route that doesn’t exist within the defined routes of the application.

How Do I Handle 404 Error in React JS?

Handling 404 errors in React is a crucial part of building a user-friendly and polished web application.

A 404 error occurs when a user attempts to navigate to a page that doesn’t exist, typically because they’ve entered a wrong URL or followed a broken link.

React doesn't automatically handle these errors out of the box, but with a little effort, I can set up a clean and effective solution.

In this guide, I'll break down how to manage 404 errors in a React app using React Router.

1.Setting Up React Router

To handle 404 errors in React, I’ll need a routing solution. React Router is the most widely used library for handling navigation in React apps, and it offers a simple and flexible way to manage routes.

If React Router isn’t already installed in the project, I can install it by running:



npm install react-router-dom


Enter fullscreen mode Exit fullscreen mode

Once React Router is installed, I can start defining the routes in my app.

2.Creating a 404 Error Page.

First, I need to create a component that will serve as the 404 error page.

This page can be as simple or as complex as I want. For now, I'll create a basic one:



// src/pages/NotFound.jsx
import React from 'react';

const NotFound = () => {
    return (
        <div>
            <h1>404 - Page Not Found</h1>
            <p>Oops! The page you are looking for does not exist.</p>
        </div>
    );
};

export default NotFound;



Enter fullscreen mode Exit fullscreen mode

This component will display a message when a user navigates to a route that doesn’t exist.

3.Integrating the 404 Page with React Router.

Now, I’ll integrate the NotFound component into my app. I want React Router to render this component whenever the user navigates to an undefined route. Here's how to do it:



// src/App.jsx
import React from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import Home from './pages/Home';
import About from './pages/About';
import NotFound from './pages/NotFound';

function App() {
    return (
        <Router>
            <Routes>
                <Route path="/" element={<Home />} />
                <Route path="/about" element={<About />} />
                {/* Catch-all route for 404 */}
                <Route path="*" element={<NotFound />} />
            </Routes>
        </Router>
    );
}

export default App;


Enter fullscreen mode Exit fullscreen mode

Here, the Routes component manages all the routes for the app. The Route with a path of "*" is a catch-all route that matches any route not explicitly defined. If a user navigates to an undefined route, the NotFound component is rendered.

4.Redirecting Instead of Rendering a 404 Page.

In some cases, I might want to automatically redirect users to a specific page (like the home page) instead of showing a 404 error page.

This can be useful for applications where I want to prevent users from seeing any broken routes.

To implement a redirect instead of displaying a 404 page, I can make use of the Navigate component from React Router:



// src/App.jsx
import React from 'react';
import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom';
import Home from './pages/Home';
import About from './pages/About';

function App() {
    return (
        <Router>
            <Routes>
                <Route path="/" element={<Home />} />
                <Route path="/about" element={<About />} />
                {/* Redirect to home page */}
                <Route path="*" element={<Navigate to="/" replace />} />
            </Routes>
        </Router>
    );
}

export default App;



Enter fullscreen mode Exit fullscreen mode

Here, instead of rendering a 404 page, the user is redirected to the home page whenever they navigate to an undefined route.

The replace prop ensures that the history stack is replaced rather than adding a new entry, which prevents users from hitting the back button and returning to the 404 page.

5.Handling 404 Errors with Server-Side Rendering (SSR).

If I'm working with a server-side rendered (SSR) React app (such as a Next.js or a custom Express + React setup), handling 404 errors requires some additional configuration.

For Next.js, for example, I can create a 404.js file inside the pages directory:



// pages/404.js
export default function Custom404() {
    return (
        <h1>404 - Page Not Found</h1>
    );
}


Enter fullscreen mode Exit fullscreen mode

This automatically handles 404 errors for routes that don’t exist. Next.js will render this page whenever a user navigates to a non-existent route.

For a custom Express + React setup, I need to ensure that the server correctly returns a 404 status code and renders the appropriate 404 page. Here's a simple example:



// server.js
app.get('*', (req, res) => {
    res.status(404).sendFile(path.resolve(__dirname, 'build', 'index.html'));
});


Enter fullscreen mode Exit fullscreen mode

This ensures that the server responds with a 404 status for any undefined route while still serving the React app.

Best Practices for 404 Error Handling.

  • Custom Messaging: A simple "Page Not Found" message works, but I can enhance user experience with some helpful messaging, like providing links to other parts of the site or a search bar.
  • Log 404s: It’s good practice to log 404 errors, so I can monitor broken links and improve navigation. Logging can be done using services like Sentry or by implementing custom logging with a backend.
  • Design Considerations: The 404 page doesn’t have to be boring! Many sites use humour, graphics, or even animations to make the experience less frustrating for the user. Keeping it light can ease the user’s frustration of not finding what they were looking for.
  • SEO Impact: Search engines take note of 404 pages, so the app must return the correct 404 status code for undefined pages. This prevents search engines from indexing them, which could harm the app’s SEO.

Conclusion.

Handling 404 errors effectively is vital for delivering a good user experience.

By implementing a custom 404 page or redirecting users when they hit non-existent routes, I can keep users engaged and guide them back to the right path in my app.

Whether working with client-side routing or server-side rendering, the tools are available to ensure the app handles 404s gracefully and efficiently.

. . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player