Don`t Fetch JSON
Why should you though? This is not intended if you have an API endpoint (backend) serving multiple types of clients(like mobile and web).
Don't use this in production. It's just an experiment.
It is a small experiment to check whether you can directly get the
html for the component instead of fetching the JSON data and populating it in the React Component. Express is used for server rendered React output.
Generally in SSR, we have the routing logic in the React application, using
react-router or some similar kind of library. The server (Express in our case) returns the complete React application for all routes and does not worry about routing.
Let's build a special route, say
/getRenderedComponent, to give the rendered HTML as a response, as a middleware.
We included it as a middleware, so the request will pass through it. (This might not be the correct way of doing this. We should have a separate route for this).
At the middleware, we render the HTML. We can even use
react-dom/renderToString and render a React component to send as a response.
This response can be consumed in a React component easily. Something which can fetch and render HTML inside it will do the job. Like our
I don't have an exact idea of where this can be put to a real production environment but was a successful fun experiment.
Thanks for reading through. Good day 👋