React With Express

Updated: 2021-01-01

Project structure

root
  - client (create-react-app) running on port 3000
  - server (express app)  running on port 8080

In Development

Add proxy to package.json, so that requests not handled by client will be redirected to server.

"proxy": "http://localhost:8080/"

Note that this only affects development, NOT the production in any way.

Then you can use fetch in client to talk to server:

fetch("/api/foo")
      .then((response) => response.json())
      .then((result) => { ... })

In Production

Add this to Express app:

if (process.env.NODE_ENV === "production") {
  app.use(express.static(__dirname + "/../client/build"));
}

create-react-app will build the static app into client/build folder. This tells the server to serve the client app as static resources.