How to serve React JS static files with express JS?

  1. Install express and create a new directory for the project.

  2. Create a new file called server.js in the project directory.

  3. Use the following code in server.js to set up a basic express server:

const express = require('express');
const path = require('path');
const app = express();

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

app.get('/*', function(req, res) {
  res.sendFile(path.join(__dirname, 'build', 'index.html'));
});

const port = process.env.PORT || 3000;
app.listen(port, () => {
  console.log(`App is running on port ${port}`);
});
  1. Install React and build the project using the following commands:
npx create-react-app my-app
cd my-app
npm run build
  1. Run the express server using the following command:
node server.js
  1. Access the React app by navigating to http://localhost:3000 in a web browser.