Skip to content

SPA 404 pages: return a real 404 in a single-page app

A single-page app that sends index.html with a 200 for every URL creates soft 404s. Here is how to return a real 404 from the server, host or framework.

By Crawlito · 9 min read

In short

  • A single-page app usually answers every URL with the same index.html and a 200 status, so an unknown URL looks like a successful page to any client that reads only the response.
  • Google defines a soft 404 as a 2xx response whose content looks like an error or an empty page, and it reports these in Search Console.
  • The reliable fix is on the server side: return the app shell only for routes that exist, and return a 404 for everything else.
  • Netlify, Firebase Hosting and Cloudflare each document a catch-all setting that serves index.html instead of a 404, so check those settings first.
  • A JavaScript redirect to a URL that returns a 404, or an injected noindex tag, is Google's documented fallback when the server cannot do better.
On this page

A single-page app (SPA) returns a 200 for unknown URLs because the server is configured to send the same index.html for every path and let the browser's router decide what to show. To return a real 404, the server, the host or the framework has to know which routes exist and answer everything else with a 404 status. A "page not found" screen drawn by JavaScript inside a 200 response does not do that.

This guide is for developers running a React, Vue or Angular SPA who see "soft 404" in Google Search Console, or who find that a random URL on their site loads the app. It covers how to test the behavior, three server-side fixes, and what to do when only a client-side workaround is possible.

Why a single-page app returns 200 for every URL

A client-side router changes the address bar with the History API. MDN's pushState reference says the browser will not attempt to load the new URL after that call, though it may attempt to load it later, for instance after the browser restarts. So while a visitor clicks around, the server is never asked about /pricing or /products/42.

The server only sees a path when someone loads it directly: a refresh, a bookmark, a link from another site, or a crawler. If the server has no file for that path, an SPA host usually falls back to index.html so deep links work. That fallback is where the trouble starts. Vue Router's history mode guide says it plainly: your server will no longer report 404 errors, because all not-found paths now serve up your index.html file. It suggests either a catch-all route inside the app or a server that responds with a 404 when no route matches.

The result is a response like this for a URL that never existed:

http
HTTP/2 200
content-type: text/html; charset=utf-8

<!doctype html>
<html><body><div id="root"></div><script src="/assets/app.js"></script></body></html>

A browser runs the script and may show a "Page not found" component. Anything that stops at the response sees a successful page. MDN's 404 reference describes 404 as the status that tells a client the server cannot find the requested resource, and it advises 410 Gone for content that is permanently removed.

What a soft 404 costs you

Google's HTTP status code documentation defines a soft 404 as a page that returns a 2xx status while its content suggests an error, such as an error message or an empty page. Search Console reports these. The same page says Google treats 404 and 410 like other 4xx codes: it does not use content from those URLs, and a URL that was already indexed is removed from the index.

A fallback 200 hands that decision to Google's classifier instead of stating it yourself. It also means invented URLs, typos and old links all return something that looks like a live page, which can hide real broken links in your own reports. For the general concept, see soft 404 pages and AI crawlers. This post covers the SPA-specific causes.

This post does not claim to know how any particular AI crawler treats a 200 error shell. A true 404 states the outcome in the response itself, so nothing is left to interpretation.

How to check what your unknown routes return

Request a path that has never existed and print only the status code. Use a clearly artificial path, and keep it out of your sitemap and internal links.

bash
curl -s -o /dev/null -w "%{http_code}\n" https://example.com/this-page-does-not-exist-7f3a

A 404 means the server is already doing its job. A 200 means the fallback is catching everything. Then test the three cases that matter:

  1. A real route, such as /pricing. It should return 200.
  2. A nonsense top-level path, such as /zzz-test. It should return 404.
  3. A plausible detail URL for something that does not exist, such as /products/does-not-exist. This one is the hardest, because the server may only know the pattern /products/:id, not whether that product exists.

Check the body as well as the status, using a plain GET as described in HEAD versus GET for crawler testing. A 404 status with a blank page is better than a 200, but a short, useful not-found page is better still. If you also need to follow redirects, the status codes and redirects guide shows how to see every hop.

Fix 1: only serve the app shell for known routes

The most direct fix is a server that keeps a list of valid routes and returns the shell only for those. Everything that is neither a static file nor a known route gets a 404.

This Node and Express sketch reads a route list that your build writes to dist/routes.json. Generate that file from the same source as your sitemap, so the two cannot drift apart.

js
import express from "express";
import { readFileSync } from "node:fs";
import path from "node:path";

const dist = path.resolve("dist");
const known = new Set(JSON.parse(readFileSync(path.join(dist, "routes.json"), "utf8")));

const app = express();
app.use(express.static(dist));

app.use((req, res) => {
  const route = req.path.length > 1 ? req.path.replace(/\/$/, "") : req.path;
  if (known.has(route)) {
    res.status(200).sendFile(path.join(dist, "index.html"));
  } else {
    res.status(404).sendFile(path.join(dist, "404.html"));
  }
});

app.listen(3000);

The same idea works in nginx. The try_files directive can end in a status code instead of a fallback URI, as the nginx core module documentation describes. Treat this as a sketch to adapt and test with the curl commands above:

nginx
server {
  root /var/www/app/dist;

  # Known routes get the app shell
  location = / { try_files /index.html =404; }
  location ~ ^/(pricing|about|contact)/?$ { try_files /index.html =404; }

  # Everything else: a real file, or a 404
  location / { try_files $uri =404; }

  error_page 404 /404.html;
}

Dynamic routes are the limit of this approach. A rule for /products/:id can confirm the shape of the URL but not that the product exists. For those routes you need a lookup (against the route manifest, a database or an API) before the server decides between 200 and 404. If you find yourself building that, Fix 3 is usually less work.

Fix 2: check the hosting settings that rewrite everything to index.html

Many static hosts make the SPA fallback a one-line setting. These are the ones to look for, with what each vendor documents at the time of writing.

HostSetting that causes itWhat the docs sayWhat to change
Netlify/* /index.html 200 in _redirects or netlify.tomlServes index.html instead of giving a 404 no matter what URL is requestedReplace the splat with explicit rules for real routes, or prerender each route
Firebase HostingA "source": "**" rewrite to /index.htmlApplies when no file exists at the path; rewrites are listed ahead of a custom 404.html in its priority orderRewrite only specific known paths, or prerender
Cloudflare Workers static assetsnot_found_handling: "single-page-application"Serves /index.html with a 200 OK statusUse 404-page, which serves the nearest 404.html with a 404 status
Cloudflare PagesNo top-level 404.htmlPages assumes a single-page app and serves the root for paths that are not static assetsAdd a top-level 404.html, give every real route its own file, and check the status with curl
Amazon CloudFrontA custom error response for 403 or 404 that serves a page such as /index.html with a 200 response codeCloudFront can return a different status to the viewer than the origin sent, including 200Do not override the code for real not-found cases; route known paths another way

Sources: Netlify rewrites, Firebase Hosting configuration, Cloudflare SPA routing, Cloudflare 404 pages, Cloudflare Pages serving and CloudFront response codes.

Two cautions apply to every row. First, removing a catch-all breaks direct loads of client-only routes unless each of those routes has a real file behind it, so pair the change with prerendering (see prerendering and dynamic rendering). Second, the Cloudflare Pages documentation says what is served but does not state the status code in that mode, so verify it with curl instead of assuming.

For CloudFront, AWS documents the response-code override but not a complete SPA recipe. If you need both deep links and honest 404s there, you will need a way to tell known paths from unknown ones before the fallback applies, such as prerendered files per route or logic at the edge. Test the result with the curl checks above.

Fix 3: use your framework's not-found handling with server rendering

If your app renders on the server, the framework can set the status itself, and the problem largely goes away.

Next.js. Calling notFound() in a Server Component stops rendering of that route segment and shows your not-found UI. The documentation says it returns a 404 when it runs before the response starts, including during prerendering, and that Next.js adds a noindex meta tag. It also documents a catch: if you call it inside a <Suspense> boundary after streaming has begun, the response keeps its 200 status. Run the existence check before streaming starts, for example in the page itself rather than a component nested under Suspense, when the status matters.

React Router framework mode. The status code guide shows a loader throwing data("Not Found", { status: 404 }) to reach the route's error boundary. That page does not describe how URLs that match no route are handled, so test an unmatched path yourself.

ts
export async function loader({ params }: Route.LoaderArgs) {
  const project = await fakeDb.getProject(params.projectId);
  if (!project) {
    throw data("Not Found", { status: 404 });
  }
  return project;
}

Vue and Angular. Check the server rendering documentation for Nuxt or Angular for the current not-found method, and confirm with curl that the HTTP status changes, not only the page content.

A framework that renders on the server also solves the empty HTML problem from client-side rendering and the empty HTML shell. The React SPA guide compares the migration options.

When a client-side redirect or noindex is the only option

Sometimes you cannot change the server: a locked-down host, a shared CDN, a third-party platform. Google's JavaScript SEO basics describes two workarounds for soft 404s in client-rendered apps.

  1. Redirect with JavaScript to a URL that returns a real 404. For example, when your API says a product does not exist, send the browser to /not-found, a path your server answers with a 404 status.
  2. Add a noindex robots meta tag with JavaScript on the error view.
js
const response = await fetch(`/api/products/${id}`);
if (response.status === 404) {
  window.location.href = "/not-found"; // must return a real 404 from the server
}

Both depend on a client that runs your JavaScript. Google also warns that when it sees a noindex tag it may skip rendering, so changing or removing a noindex with script may not work, and non-200 pages may not be rendered at all. Treat these as a fallback for Google, not a fix: a client that does not execute scripts never sees the redirect or the tag, and the original response was still a 200. For how often that applies to AI crawlers, see the evidence in the React SPA guide linked above.

How to verify the fix and watch for regressions

  1. Re-run the three-URL curl test after every deploy that touches routing, hosting rules or CDN settings. Put the commands in CI so a change that reintroduces a catch-all fails the build.
  2. Check the cached copy. A CDN can keep serving the old 200 from cache. Request the URL with a cache-busting query string to compare, and purge affected paths if needed.
  3. Look at Search Console for soft 404 reports on the affected URLs. A report can lag behind your deploy, so a lingering entry is not proof the fix failed. Use a live test of the URL to see the current response.
  4. Check your internal links. If a 404 appears in your own navigation, fix the link. A route that moved should redirect to its replacement, and a page that is gone should return 404 or 410. See internal links and broken links for how to find them.

Fixing the status removes one source of ambiguity. It does not determine when a search system re-crawls the URL or whether it appears in any result.

Frequently asked questions

Does a custom 404 component inside my React app count as a 404?

No. The status code is set by the HTTP response, before your JavaScript runs. A not-found component inside a 200 response is still a soft 404 candidate under Google's definition of an error-looking page with a success status.

Should I use 404 or 410 for pages I deleted?

Both work. MDN says a 404 does not say whether the absence is temporary or permanent and recommends 410 for permanent removal. Google's documentation says it treats 404 and 410 alike, so choose based on your own intent.

Is a redirect to the homepage better than a 404?

Not for pages with no real replacement. A redirect says the content moved. Send a redirect only when a closely matching page exists, and return a 404 otherwise.

Can I return a 404 from a purely static site with a client-side router?

Only for URLs that have no file and no catch-all rule. If every deep link must load the app shell, the host cannot tell valid from invalid routes without extra configuration or prerendered pages per route.

Test your own URLs

The free check reads one page the way a crawler does, with no account needed, so you can see the status code and raw HTML a given URL returns. To run the same checks across up to 500 pages with evidence and prioritized fixes, an audit covers a whole site.

Filed under Rendering and content. Topics: javascript, react, http-status, rendering, troubleshooting, ssr