DEV Community

mustafa morbel
mustafa morbel

Posted on Originally published at Medium

Effectively Managing 404 Errors on the Server-Side in React SPAs with Nginx

Originally published on Medium (Medium). Read on Medium for free via Friend Link.

☕ Explore Developer Starter Kits & Guides

Quick Takeaways

  • Stop Masking 404s as 200 OK : Default SPA fallback rules return index.html with a 200 OK status for missing URLs, blinding server monitoring and hurting SEO.
  • Bridge React Router & Nginx : Pair a catch-all client route that redirects to /404 with an Nginx error_page 404 /404 block so the server logs a true 404 while the SPA renders your not-found UI.
  • Track Broken Routes in Logs : Use Nginx access_log and error_log to uncover dead links across React, Vue, or Angular deployments.

Diagram illustrating how a Single Page Application and Nginx coordinate to return real server-side 404 status codes
illustration : Tisna Permadi

Problem Definition

When a user tries to directly access a specific address in an SPA, the server cannot find a matching HTML file for that path and would normally return a 404 error. However, most SPA setups are configured to handle this by returning the application's main index.html instead of a 404 page.

This keeps navigation smooth for the user, but it creates a blind spot for server-side monitoring and error-logging systems. The result? Your server reports a healthy 200 OK response even though the route does not actually exist.

In this article, we will walk through how to effectively manage 404 errors on the server side in your SPAs, broken into four parts: SPA routing basics, React Router catch-all configuration, Nginx redirection, and server-side error tracking.


SPA and Routing: Basic Operation

SPAs provide a seamless experience by dynamically loading all application content through a single HTML page. However, the server's unawareness of client-side routes can lead to silent 404 issues on direct URL access.

Left unhandled, this creates serious problems for server-side error logging, search engine indexing, and user experience. Understanding that gap between client-side routing and server-side responses is the first step toward fixing it.


React Router Configuration for 404 Error Handling

React Router gives us a clean way to catch unknown paths in an SPA. Below is a complete example demonstrating how to configure a catch-all route that renders a dedicated PageNotFound component:

import React from "react";
import { Route, Link, Routes } from "react-router-dom";

export default function App() {
  return (
    <div>
      <nav>
        <ul>
          <li>
            <Link to="/">Home</Link>
          </li>
          <li>
            <Link to="/about">About</Link>
          </li>
          <li>
            {/* Link to catch-all route */}
            <Link to="/does-not-exist">
              Catch all route
            </Link>
          </li>
        </ul>
      </nav>

      <Routes>
        <Route path="/about" element={<About />} />
        <Route path="/" element={<Home />} />

        {/* Match when no other routes match */}
        <Route path="*" element={<PageNotFound />} />
      </Routes>
    </div>
  );
}

function Home() {
  return <h2>Home</h2>;
}

function About() {
  return <h2>About</h2>;
}

function PageNotFound() {
  return (
    <div>
      <h2>404 Page not found</h2>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

The <Route path="*"> component routes all undefined paths to PageNotFound. When a user enters an invalid URL, they see a clear 404 page inside the app.

However, that alone still leaves the server returning 200 OK. To involve Nginx, using window.location.href = "/404" forces a full browser request so the server sees the /404 path first. We can update the catch-all route as follows:

<Route path="/404" element={<PageNotFound />} />
<Route
  path="*"
  element={() => {
    return <>{(window.location.href = "/404")}</>;
  }}
/>
Enter fullscreen mode Exit fullscreen mode

Once the request hits /404 on the Nginx side, the server can record a genuine 404 status while still serving the SPA bundle so React renders the PageNotFound view.


Nginx Configuration for SPA Redirection

Nginx makes it straightforward to combine SPA fallback routing with proper server-side 404 handling. In the configuration below, normal routes fall back to index.html, while /404 is handled explicitly via error_page:

server {
    listen       80;
    server_name  localhost;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
        try_files $uri $uri/ /index.html;
    }

    error_page 404 /404;

    location = /404 {
        internal;
        root   /usr/share/nginx/html;
        try_files /index.html;
    }
}
Enter fullscreen mode Exit fullscreen mode

In this configuration, try_files tells Nginx to look for the requested URI first, and if no static file exists, to serve index.html. Marking location = /404 as internal ensures it is only triggered through Nginx's internal error handling.


Application for Different Types of SPAs

This same pattern applies to SPAs built with other JavaScript frameworks such as Vue and Angular. While each framework has its own client-side router syntax, the Nginx and container setup stays largely the same: route invalid paths to a dedicated /404 endpoint so the server and browser stay in sync.


Server-Side Tracking of 404 Errors

Once Nginx is aware of 404s, its built-in logging becomes far more useful. The access_log and error_log directives let you see exactly which missing URLs users and crawlers are hitting—giving you concrete data to fix broken links, tighten redirects, and protect your SEO strategy.

How does your team handle server-side 404s in production SPAs — Nginx rules, edge middleware, or SSR? I'd love to hear your thoughts 🧠💬


Keep Exploring

If you found this guide helpful, check out these related React and TypeScript resources:


About the Author

I'm Mustafa Morbel — Senior Frontend Engineer with over 17 years of experience building scalable React architectures, WebGL applications, and resilient web systems.

Top comments (4)

Collapse
 
michael1980 profile image
Toolmaster •

Two details worth checking before copying the snippets:

  1. try_files /index.html; in location = /404 won't load: try_files needs at least two arguments (files plus a final URI or =code), so nginx -t rejects it. try_files /index.html =404; works, and because the request reached that location via error_page 404, the 404 status is kept.

  2. In React Router v6, element expects a React element, not a function. element={() => ...} renders nothing (React warns that functions aren't valid children), so the redirect never fires. A small component does it: function RedirectTo404() { useEffect(() => { window.location.replace('/404'); }, []); return null; } with element={<RedirectTo404 />}.

One trade-off to keep in mind: the original missing URL still answers 200 with index.html, and the 404 shows up in the access log under /404, not under the path that was actually broken. Clients that don't run JavaScript (curl, most link checkers) still see a soft 404 there. Passing the path along, e.g. /404?from=/does-not-exist, at least keeps it in the logs. For Googlebot, which renders JavaScript, a JS redirect to a URL that returns a real 404 is one of the options Google documents for single-page apps.

Collapse
 
mkare profile image
mustafa morbel •

Good catch—thanks for pointing out the try_files syntax nuance (try_files /index.html =404; so nginx -t accepts the fallback argument) as well as the React Router v6 element wrapper detail. Passing the original path along in a query param like /404?from=... is also a practical touch for keeping track of what actually broke. I'll definitely keep this in mind and clarify the snippet!

Collapse
 
linkbruno profile image
linkbruno.com •

Careful with the window.location.href = "/404" step if the goal is finding dead links in the logs. The broken URL people actually requested gets logged as a 200, and the 404 line that follows is for /404 itself, so every dead link ends up as the same path. You can dig the real one out of $http_referer on that line, but crawlers that don't run JS never even get that far, they just see a 200.

The setup that worked better for me was letting Nginx know which route prefixes exist (a few location blocks or a map) and only falling back to index.html for those, with everything else going straight to =404. Then the bad URL itself carries the 404. Have you tried something like that, or does the route list change too often to keep it in the config?

Collapse
 
mkare profile image
mustafa morbel •

You're completely right—with the client-side redirect, the original broken path gets logged as 200 and only /404 shows up as 404, which muddies dead-link analytics and leaves non-JS crawlers seeing a soft 404. For clean server-side tracking, matching known route prefixes directly in Nginx (or returning 404 at the edge/SSR layer) is definitely the cleaner architecture. In setups where the route list is fairly stable, maintaining a map or prefix block in Nginx is well worth it.