Server-side rendering with create-react-app, code-splitting, preloaded data, React Router, Helmet, Redux, and Thunk
I feel we’ve been here a million times before. Your brand new web application is served hot and ready in the cloud. Component structure is well-organized. UI is on fleek. But Facebook’s sharing debugger throws shade.
I’ve spoken about this before. For a million and a half reasons you cannot seem to get social networks and some search engines to play nice and just respect your damn content. Here we are again, with the latest toys and a few new additions. If you want to read about why server-side rendering is necessary for many deployed applications, feel free to read my previous article. In this tutorial, I’ll mostly be hopping around showing off individual portions of how to accomplish the greater goal. If you want the full picture, head over to the Github repo. You can also view the final product in all it’s beautiful form.
I set out to create the best damn server-rendered create-react-app application possible. Easier said than done.
- Zero modifications to your existing CRA application
- Create React App without ejecting
- React 16 (fiber, baby!)
- React Router v4 (with Thunk, via Connected React Router)
- Full SEO support via React Helmet
- Preloaded page data via async/await and React Frontload
- Code splitting via React Loadable
- Server-side cookie support
Let’s roll through these for brevity sake.
Zero modifications: When I say “zero modifications”, I mean that if you want to render a React app on the server, all you “technically” need to is to add one folder with three files. If you want a few nice toys like preloaded page data and code splitting, we can do so with minimal additional effort.
React Fiber: We’re using the latest and greatest version of React: 16.4. This means access to
hydrate and other sexy performance upgrades. Love it.
React Router: React Router allows us a super simple, declarative way of routing. This is tied directly to Redux via Connected React Router. Instead of using
BrowserRouter, we use
ConnectedRouter on the client-side and
StaticRouter on the server.