Home > database >  Deploy production build of ReactJS with Node express as backend
Deploy production build of ReactJS with Node express as backend

Time:09-16

Hi even after lot of search i am still confused what is correct way to deploy my react app created using create-react-app with express as backend. I ran npm run build which created build folder. I copied the build folder to be served as static folder of express and had put app.use(express.static('build'));. It is working fine for homepage, that is homepage opens when i run my express node server but when i go to anyother link outside homepage it gives 404. Everything is working fine in developer mode, which i run by npm start command. I just want to know what i am doing wrond here. Let me know anymore info required to understand the problem. Thankyou.

CodePudding user response:

It sounds like you don't have the backend server running. You need to npm start your server, and then npm start your front end if that make sense. They are 2 separate things.

CodePudding user response:

Are you using client-side routing? A popular implementation of that is react-router.

Let say you are trying to access /page1, what client-side routing does is use the JS to toggle between different components to "fake" the routing, instead of rending a new HTML.

Yet, by default when you change routes, the browser does the usual stuff and send a GET request to the server asking for the corresponding HTML file. But since you only have index.html served, that's why you received 404.

You need to add the following at the end of your app.js, right before you call app.listen of your express server to tell the server to always return index.html no matter what route does it received.

/* client-side routing. 
 * For GET requests from any routes (other than those which is specified above),
 * send the file "index.html" to the client-side from the folder "build"
 */
app.get("*", (_, res) => res.sendFile("index.html", { root: "build" }));

// your usual app.listen
app.listen(port, () => console.log("Listening"));
  • Related