How to Handle Routing on Deployment in React
react-router, you must configure your web server to serve index.html for all routes. This ensures the React app handles routing instead of the server returning 404 errors for client-side paths.Why This Happens
React apps using client-side routing rely on the browser to handle URL changes without asking the server for new pages. When you refresh or directly visit a nested route, the server tries to find a matching file and often returns a 404 error because it does not know about client-side routes.
import { BrowserRouter, Routes, Route } from 'react-router-dom'; function App() { return ( <BrowserRouter> <Routes> <Route path="/" element={<Home />} /> <Route path="/about" element={<About />} /> </Routes> </BrowserRouter> ); } export default App;
The Fix
Configure your web server to serve index.html for all routes. This lets React handle routing on the client side. For example, in an Apache server, use a .htaccess file with a rewrite rule. For Netlify, add a _redirects file. For Vercel, routing is handled automatically.
# Apache .htaccess example
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
# Netlify _redirects example
/* /index.html 200Prevention
Always plan your deployment with client-side routing in mind. Use static hosting services that support SPA routing or configure your server properly. Test your app by refreshing nested routes before deploying. Use HashRouter as a fallback if server configuration is not possible, though it changes URLs.
Related Errors
404 on refresh: Server does not serve index.html for client routes.
Blank page on nested routes: React app fails to load due to wrong base path.
Incorrect asset loading: Use basename prop in BrowserRouter if app is served from a subfolder.