ReactRender: Server Side Rendering for React Components

Hi @Harrisonl,
Thanks for checking it out!

Yea it is pretty similar to NextJS, but NextJS is IMO better suited for something fully static, and served entirely from CDN, or maybe the new serverless idea they are pushing. But deploying NextJS as part of an Express application or the like is not recommended, because of the synchronous rendering of React components to a string in Node.

Thing is, I need/want to reach down to the underlying HTTP constructs for security purposes, like cookies, CSRF, redirects, server side auth etc..

This pattern lets me leverage Phoenix/Plug and its great patterns and structure for managing HTTP/API concerns, and delegating the UI/UX to server rendered + client hydrated React. Which despite its pitfalls, has enormous engineering effort/community behind it…

I currently work on a team that has too much React experience to toss it away. As much as I love the idea of LiveView; I also appreciate the inherent separation between front and back-end code the SPA pattern benefits from, and how it allows for teams that can specialize in say React or Elixir.

To directly answer the questions:
<ClientContainer /> is used to hydrate React on the client. This is necessary because certain React provider components, namely react-routers StaticRouter vs BrowserRouter.

The StaticRouter is used for server rendering and pretty much just takes a location(path) as a prop, and figures out what page of the React app to render. The linked example is using a wildcard phoenix route,to pass the conn.request_path into the ServerContainer so it knows what page to render.

The ClientContainer uses BrowserRouter, which is actually hooked up to the browsers push state history stuff and grabs its location from the URL bar.

So yes, the component is rendered on the server with the data you provide it.
During rendering the component on the server, it could also do some data fetching from within the servers node environment.

It is still possible to deliver the app.js, and app.css webpack bundles over CDN, just not the rendered HTML page. And yes, the app can be bootstrapped entirely on the server, removing the need for a initial API call to understand who is on the page or for critical data for example.

The rendered HTML could be cached in Elixir - but depending on the state it is hydrated with - e.g private user information. It might not be a good idea to be naively caching it, it does however have a pretty substantial performance improvement if it was necessary.

Happy to answer any more questions!

Oh, and to clarify phoenix actually returns the rendered react component - so not an empty html page. You can verify this when looking at the data over the network, or the initial page load.

1 Like