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
- Frontend production build into
build
or other folder - Backend serve under path
api
the default returnindex.html
and serve static content inbuild
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
- Serve static content in
build
folder e.g. pages, images, fonts, icons - Write API as usual.
This can be in the separate folder likeserver
,backend
or other naming. - 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!