0
0
ReactDebug / FixBeginner · 4 min read

How to Handle Routing on Deployment in React

When deploying a React app using client-side routing with 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.

jsx
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;
Output
Refreshing or visiting /about directly shows a 404 Not Found error from the server.
🔧

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.

plaintext
# 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   200
Output
All routes serve index.html, so refreshing /about loads the React app without 404 errors.
🛡️

Prevention

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.

Key Takeaways

Configure your server to serve index.html for all client-side routes to avoid 404 errors on refresh.
Use rewrite rules or redirect files depending on your hosting environment.
Test routing by refreshing nested URLs before deploying your React app.
Consider HashRouter if you cannot configure the server, but it changes URL appearance.
Set basename in BrowserRouter if your app is served from a subfolder.