How to serve ReactJS static files with expressJS? How to serve ReactJS static files with expressJS? reactjs reactjs

How to serve ReactJS static files with expressJS?


After trying many different things through trial/error, the solution is quite simple:

Serve the /client/build folder in the static call, like so:

app.use(express.static(path.join(__dirname, '../client/build')));


I had the same problem for a while and I would say that the solution that works is divided into 2 parts to avoid problems with the routers

  1. Server the static from the CRA build (in your case the client/build)
const buildPath = path.normalize(path.join(__dirname, '../client/build'));app.use(express.static(buildPath));
  1. Set a final route (after all other routers in your server) to use the following:
const rootRouter = express.Router();/* * all your other routes go here*/rootRouter.get('(/*)?', async (req, res, next) => {  res.sendFile(path.join(buildPath, 'index.html'));});app.use(rootRouter);


//on your react app run

npm run build

//The insert the following code on your server

const path = require("path");app.use(express.static(path.join(__dirname,"nameOfYourReactApp","build")))//Replace nameOfYourReactApp with the name of your app