React and routing

I made a simple React app, served from express using create-react-app. The react app has several pages: /blog, /about, for example. I’m using React Router to switch between routes on the client side.
I’m not sure what I should be doing on the server side. If you refresh “/blog” for example, the server won’t know what to do with that, so the request to “/blog” fails at the server and never makes its way back to the React app. I came up with this solution to serve a static folder from express for each route:

app.use('/blog", express.static(__dirname + 'build'"))
app.use("/about", express.static(__dirname + 'build"))

etc. for each route on the client side, such that everything will point back to the static folder and React Router can handle it from there. I’m told this approach is “wrong” by the Stack Overflow community but can’t find any good information on best practice for this sort of thing. Can anyone advise me or point me in the right direction?

You’re getting this slightly muddled I think. React is generally for building single page apps. React router provides an interface to use the browser’s history API to give the impression of separate pages, but they’re still effectively just one HTML page. You’re rendering separate HTML pages on the server, so React Router is redundant. Either serve a single index page as the only HTML generated by Express, and serve the routes as JSON (ie build a REST API). Or if you want multi-page React apps on your Express server, then something like Next.js would be sensible


After I quick scan of the docs, nextjs definitely seems like something I’ll want to be able to use. I’ll play around with it later. Thanks for pointing me in the right direction. Definitely more helpful than the answers I got on Stack Overflow.

1 Like