如何处理Create React App+Express部署到Heroku的路由问题?
Hey there, I’ve dealt with this exact problem plenty of times when deploying create-react-app (CRA) projects with an Express backend to Heroku. Let’s break down why this happens and how to fix it quickly.
Why This Happens
When you’re running locally, CRA’s dev server automatically handles routing—any request that isn’t an API call gets redirected to index.html, letting React Router take over. But on Heroku, your Express server is the one handling all incoming requests. If you don’t explicitly tell it to send index.html for non-API routes, it’ll treat paths like /dashboard as backend endpoints (which don’t exist) instead of passing them to your frontend router.
Step-by-Step Fix
1. Serve React’s Static Build Files First
First, make sure your Express server is serving the static files from your CRA’s build folder. Add this code to your Express server file (usually server.js or app.js):
const path = require('path'); // Serve static files from the React app build directory app.use(express.static(path.join(__dirname, 'client/build')));
Adjust the path (client/build) to match your project structure. If your CRA is in the same root as Express, use path.join(__dirname, 'build') instead.
2. Add a Fallback Route for Frontend Routing
Next, add a catch-all route that sends index.html for any request that isn’t an API endpoint. Important: This needs to come after all your API routes—you don’t want it overriding your backend endpoints!
// Catch all other routes and return the React app's index.html app.get('*', (req, res) => { res.sendFile(path.join(__dirname, 'client/build', 'index.html')); });
This tells Express: "If none of the API routes match this request, send the React app’s entry point, and let React Router handle the rest."
3. Verify Your Heroku Deployment Scripts
Double-check your root package.json (if you’re using a monorepo setup) to make sure Heroku runs the build command for your CRA during deployment. It should look something like this:
"scripts": { "start": "node server.js", "build": "cd client && npm install && npm run build" }
Heroku will automatically run npm run build during deployment, which generates the optimized static files in the build folder.
4. Test It Out
Deploy your updated code to Heroku, then try accessing https://consumesafe-dev.herokuapp.com/dashboard directly. It should now load the React app and render the Dashboard page via your frontend router, instead of hitting the Express server directly.
Quick Notes
- Always keep the catch-all route last in your Express route definitions—this ensures API requests are processed before falling back to React.
- If you’re using React Router’s
BrowserRouter(which you likely are), this setup works perfectly. If you’re usingHashRouter, you won’t run into this issue, butBrowserRouteris cleaner for production URLs.
内容的提问来源于stack exchange,提问作者Asernow

