Appendix B. Server-side React Router

 

From an isomorphic app standpoint, one of the difficult parts of moving to React Router 4 is that the maintainers and community at large have yet to arrive at a consistent set of best practices for data prefetching patterns. You’ll see this sentiment over and over in the documentation; for instance, the React Router Config readme file states: “There are a lot of ways to do server rendering with data and pending navigation, and we haven’t settled on one.”

Chapter 7 teaches you how to prefetch data on the server so that it’s available at render time. This appendix shows you how to do that with React Router 4. The code for the example here can be found in the repo at http://mng.bz/S3N0, in branch chapter-7-complete-react-router-4 (git checkout chapter-7-complete-react-router-4).

React Router 4 allows you to prefetch your data on the server before rendering. In the setup I suggest in appendix A, you use matchRoutes from React Router Config to prefetch data in the browser. You do the same thing on the server! This allows you to have consistency on the server and the browser because you’re using the same approach via the utility functions provided in the library. This function is synchronous, unlike the asynchronous route match function in React Router 3. (If you want consistency for your Node.js app, you could always wrap it so it returns asynchronously.) The following listing shows how to update the code to work with React Router 4.