Andrew's Digital Garden

Server Side Rendering React

A quick primer on how [[20220912120502-server-side-rendering]] works with [[react]].

The high level overview is:

  1. A client sends a request to the server
  2. Server (usually [[node]] + Express) turns JSX into HTML using ReactDOM.renderToString
  3. HTML is returned to the client
  4. Browser renders the HTML
  5. Browser requests the client-side [[js]] bundle (usually named something like client.js) and downloads it from the server
  6. Browser hydrates the HTML using ReactDOM.hydrate, making it interactive
  7. Client side React can then kick in, for data fetching, etc. Note that data fetching can also be done on the server, but it's usually more complicated.

By default [[node]] + Express has a few issues being a React SSR server. For one, the way it handles imports is different. A second issue is that it needs to handle JSX. There are a couple ways to solve this:

  • Build your server using a separate [[webpack]] config
  • Use a tool like [[babel]] to do transpilation on the fly

Since hydration needs the server and client code to match, this means you'll need to share an App component (or similar) between them.

Remember by default the client bundle that is requested by the client is going to be large. Tools like [[20220911060950-code-splitting]] and [[20220912112727-lazy-loading]] help here.

https://emergent.systems/posts/ssr-in-react/

[[buildtooling]] [[deployment]] [[rendering]]

Server Side Rendering React