React and Node Express in the Same Repos

Web development Jul 4, 2023

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

  1. Frontend production build into build or other folder
  2. Backend serve under path api the default return index.html and serve static content in build folder

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

  1. Serve static content in build folder e.g. pages, images, fonts, icons
  2. Write API as usual.
    This can be in the separate folder like server , backend or other naming.
  3. The other path will return index.html
    The 404 not found will handle by frontend routing

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!

Tags

TeamCMD

We are CODEMONDAY team and provide a variety of content about Business , technology, and Programming. Let's enjoy it with us.