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.
build
or other folderapi
the default return index.html
and serve static content in build
folderAs an example, the create-react-app
have the command build
to create the production bundle and files into build
folder
yarn build
Now we have the build
folder, so we have to
build
folder e.g. pages, images, fonts, iconsserver
, backend
or other naming.index.html
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!