Recommended way for using Express.js with React.js?

Viewed 421

I have found two ways to combine React and Express:

[OPTION 1] ExpressJS serve React static files

Fundamentally, the idea here is to have pre-compiled JavaScript files at your disposal before spinning up the server. And then in Express middleware:

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

And then in tandem have other endpoints that execute logic on server-side.

[OPTION 2] Host React files separately

Basically, decouple the logic in entirety of Frontend and Backend with one server just for serving static JS files. And then another Express server for running any queries against the database. And returning simple JSON responses.

Which one is the recommended way? Is there an advantage of using one approach over the other?

1 Answers

This is an opinionated question, and so I can only give an opinionated response.

I personally recommend OPTION 1 because you'll run into Cross-Origin-Resource-Sharing (CORS) issues in a number of places when you decouple your front and back ends. This isn't to say that it can't be done, but it will be an annoying thing you'll have to deal with.

With option 2 you'll also most likely have to be sending any requests to your back end with absolute URL paths, which can be very tough to maintain when an application scales.

With option 1 you'll have more flexibility, less to maintain, and less annoying workarounds to implement.

Related