React Server-Side Rendering

Image of Author
March 6, 2022 (last updated September 21, 2022)

Manual Server-Side Rendering (SSR) with ReactDOM API

React server-side rendering (SSR) can seem pretty magical, and while I don't understand the intricate details, at a high level it's doing something simple and common: Rendering server-side html and sending it to the client. In fact, you can use React as a server-side templating engine simply by calling ReactDOMServer.renderToStaticMarkup(Element(props)) (see more below). It only gets slightly more complicated for SSR, since React will want to have react-internal code passed down with the express intent of attaching normal event-listeners, so that React "turns on" once it gets to the front end. This can be done manually with ReactDOMServer.renderToString() on the server, and ReactDOM.hydrate() on the client.

React as a Next.js server-side templating engine

This is an example of how you could use React server-side (via Next.js) as a templating engine. For example, you could generate HTML email templates like this.

npm i react-dom/server
// pages/api/template.js

import ReactDOMServer from "react-dom/server";
import EmailComponent from "../src/emails";

export default function handler(req, res) {
  const props = req.query; // req.body.props, etc.
  const html = ReactDOMServer.renderToStaticMarkup(
    EmailComponent({ ...props })
  );
  res.status(200).send(html);
}

Resources

https://reactjs.org/docs/react-dom-server.html#rendertostaticmarkup

https://nextjs.org/docs/api-routes/api-middlewares

https://nextjs.org/docs/api-routes/response-helpers

https://reactjs.org/docs/react-dom.html#hydrate