React and Node Express in the Same Repos

Normal practices is separating frontend and backend into different repos.

But there is time you have to combine and here is the way to do it.

Approaches

React.js App

As an example, the create-react-app have the command build to create the production bundle and files into build folder

yarn build

Express.js

Now we have the build folder, so we have to

With this approach

GET /api/x/y/z --> handle by express
POST /api/x/y/z --> handle by express
GET / --> index.html
GET /frontend/page --> index.html react route to that page
GET /unknown/path --> index.html react handle route to 404

Here is the simplest version of code

const express = require("express")
const app = express()
const path = require("path")
// Serve static content
app.use(express.static("build"))
// Write api as usual
app.get("/api", (req, res) => {
return res.json({ message: "this is api path" })
});
// other path
app.use("/", (req, res) => {
return res.sendFile(path.join(__dirname + "/build/index.html"))
});
app.listen("3333", () => {
console.log("running on 3333")
})

This is for the production.

For development, we need to hot reload with the backend. I will write the convenient way to do it with docker-compose in another article (… soon in my TODO list)

Hope this help!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store