React: Connect React-Router, Node, and Express so all URIs Served
Problem: I’m trying to run my React app on a Node/Express web server, but when I try to navigate to a page other than root, it says the resource couldn’t be found. When I navigate to it through links within the app, it works. How can I serve my React app using React-Router with Node and Express?
Solution: The issue here is that when you navigate from an external source to a URL, your basic Express/Node setup will try to serve the static pages that the URL points to. However, because react-router is dynamically generating the HTML, it’s likely that the URL doesn’t actually point to where the correct files are located.
Essentially, we have to tell Express to serve the root of our React application regardless of the URL path it receives and to then pass that path on to React-Router so it can deal with it.
Here’s a gist:[https://gist.github.com/SIRHAMY/56744f867efc6c0616e55dcc87752f9b]
The key part is the
app.get('*'... section. This is where we set index.html (the root of our React app) as the default resource to serve regardless of the path we’re at. From there, react-router can take over and deal with the app state.