Why does a deployed single-page app return 404 on refresh, and how do you fix it?
BeginnerBuild tools: webpack and Vite interview questionBy UIRound, updated 21 November 2026
Short answer
A single-page app has one real HTML file, index.html, and the router draws every other URL in JavaScript. Clicking a link works because the browser never asks the server for the new path. A refresh or a shared link sends /users/42 to the server, and a plain static host has no such file, so it returns 404. The fix is a history fallback: rewrite unknown paths to index.html.
Why it works locally and breaks in production
With React Router or any history-based router, navigation calls history.pushState, which changes the address bar without a request. How client-side routing works in React explains that part, and building a router on the History API shows it from scratch.
The Vite dev server and vite preview both include a history fallback for single-page apps, so a refresh on /users/42 locally returns index.html and everything looks fine. The production host is a different server with its own rules. Most static hosts and object stores only return files that exist, so the first refresh on a deep link is often how people discover the problem.
The fix: rewrite to index.html
Configure the host so that any path that is not a real file returns index.html with status 200. The router then reads the URL and renders the right page. It must be a rewrite, not a redirect: the address bar has to keep /users/42.
Netlify. Add a _redirects file to Vite's public/ folder so it is copied into dist/:
/* /index.html 200Netlify does not apply this rule when a file exists at the path, so real assets are still served.
Vercel. Add a rewrite in vercel.json. Files that exist in the output are served before rewrites apply:
{
"rewrites": [{ "source": "/(.*)", "destination": "/index.html" }]
}nginx. Try the file, then a directory, then fall back:
location / {
try_files $uri $uri/ /index.html;
}
location /assets/ {
try_files $uri =404; # a missing asset should be a real 404
}Apache. FallbackResource /index.html in the site config or .htaccess does the same job.
Object storage behind a CDN. Buckets have no rewrite rules of their own. A common setup maps the "not found" or "access denied" error to /index.html with status 200 at the CDN, or uses an edge function that rewrites paths without a file extension. Mapping errors works but also hides real missing files, so an edge rewrite is cleaner.
Set Cache-Control: no-cache on index.html so a new deploy is picked up, and long immutable caching on the hashed files in assets/. Choosing Cache-Control for hashed assets and HTML covers the headers.
Keep real 404s for assets
A fallback that is too broad causes a confusing error. If an old tab requests /assets/Settings-0c3b9e77.js after a deploy removed it, a catch-all returns index.html with status 200, and the browser reports something like "Expected a JavaScript module script but the server responded with a MIME type of text/html". Exclude the asset folder from the fallback, as in the nginx example, and keep recent builds on the server for a while. Catching failed chunk loads in the app and offering a reload is covered in lazy-loading routes and retrying failed chunks.
The app also has to render its own not-found page, because the server now answers 200 for every unknown path. Add a catch-all route:
{ path: "*", element: <NotFound /> }For pages that need to rank in search, a JavaScript-only 404 is a "soft 404". If that matters, prerender or server-render those routes so the server can send a real status.
The base path trap
The same refresh can fail in a second way: the HTML loads but the scripts do not. That happens when the app is deployed under a subpath, such as https://example.com/app/, but built for /, or built with relative asset URLs. On /app/users/42, a relative ./assets/index.js resolves to /app/users/assets/index.js, which does not exist.
Build with the real deploy path as base, point the fallback at that folder's index.html, and give the router the same base:
// vite.config.ts
export default defineConfig({ base: "/app/" });location /app/ {
try_files $uri $uri/ /app/index.html;
}Configuring path aliases and the base path in Vite walks through base, import.meta.env.BASE_URL and the router's basename.
Hash routing when you cannot configure the host
Some hosts allow no rewrites at all. Hash routing avoids the problem, because everything after # never reaches the server: https://example.com/#/users/42 always requests /.
import { createHashRouter, RouterProvider } from "react-router-dom";
const router = createHashRouter(routes);
export const App = () => <RouterProvider router={router} />;It works anywhere, but URLs look worse, the hash is no longer available for in-page anchors, and search engines treat everything as one page. Use it for internal tools or demos, and prefer a history fallback for public sites. Some static hosts let you serve a custom 404.html; copying index.html to 404.html makes deep links render, but the response status is still 404.
Common follow-up questions
Why does the home page work but not other pages?
/ maps to index.html, which exists. Every other route only exists inside the JavaScript router, so the server has nothing to return until you add the fallback.
Is a redirect to / with the path in a query string a good fix?
It works, but the app has to read and restore the path on load, and users see the URL change. A rewrite is simpler and keeps the URL intact.
Does Next.js have this problem?
Not when it runs on a server, because every route is a real route on the server. A static export with client-side routing can hit it on hosts that do not map paths to the generated HTML files.
Does scroll position survive the refresh?
That is a separate concern from the 404. Browsers restore scroll on reload for normal pages, but single-page apps often need to handle it themselves; see restoring scroll positions in a single-page app.
Mistakes to avoid
Using a redirect instead of a rewrite, so every deep link lands on the home page
A catch-all fallback that also returns HTML for missing JavaScript and CSS files
Building with
base: "/"and deploying under a subpathLong cache headers on
index.htmlForgetting a client-side not-found route once the server answers 200 for everything
Sources
Practise it in code
Interviewers rarely stop at the definition. These questions open in an editor with tests.
- Implement a basic client-side router using the History APIMedium45 min
- Choose
Cache-Controlheaders for hashed assets, HTML and API responsesMedium25 min - Lazy-load route components with React.lazy, preload on hover and retry failed chunksMedium40 min
- Build a route matcher with params, optional segments and wildcards, ranked by specificityMedium35 min
- Restore scroll positions in a single-page app: save per history entry, restore on Back, reset on new navigationMedium40 min