Why React Router Breaks on Page Reload (and How to Fix It)
By hungpd, at: June 1, 2025, 6:16 p.m.
Estimated Reading Time: __READING_TIME__ minutes


Problem:
In a React app using React Router (e.g., with BrowserRouter), the app works perfectly when you click links. But when you refresh the page or navigate directly to a URL like /joblist, your server returns a 404 Not Found error.
Cause:
React Router is a client-side routing solution. The browser makes a request to the server for /joblist, but the server doesn’t recognize that path. It doesn’t know it’s supposed to serve your React app and let React Router handle it.
Solution: Redirect All Routes to index.html
You need to configure your web server (Apache, Nginx, Express, etc.) to serve index.html for all unknown paths. This way, React Router will take over routing once the app loads.
Example (Nginx):
location / {
try_files $uri /index.html;
}
Example (Express.js):
app.use((req, res, next) => {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
Pros and Cons of This Solution
Pros
-
Fixes the 404 issue completely on refresh or direct URL access.
-
Works seamlessly with React Router’s BrowserRouter, enabling clean URLs without #.
-
Improves SEO and shareability of URLs (compared to hash-based routing).
-
Simple setup for most static hosts like Netlify, Vercel, or Firebase Hosting (they have built-in rewrite rules).
Cons
-
Requires server configuration, which may not be accessible in some shared hosting environments.
-
Can’t be used directly with traditional server-side routes, unless carefully handled (e.g., API routes must be excluded).
-
May expose all paths to React, which could be undesirable if you have secure or restricted server-only routes.
-
Not suitable for static file-only hosting (e.g., basic S3) unless rewrite rules are enabled.
Final Thoughts
If you’re using BrowserRouter in production, configuring your server for SPA (Single Page Application) routing is essential. This fix is industry standard but it does require awareness of how your server handles routing.
If you’re using Netlify, Vercel, or Firebase, let me know - w can give you the exact rewrite rules. Would you like that?