My team would be rendering React views on the server, for SEO purposes. I have a good experience with React, but have never been to the backend land. I know what SSR is, but I don’t know the “How” part?
How did you approach learning SSR for the first time?
Basically, you have to familiarise yourself with few concepts related to SSR:
You can find a lot of blog post about the subject, but the best way is to get your hands dirty and start coding after you understand the concepts above.
I have started to write a short recap about the subject, it's a work in progress but you can still check it out here:
This problem can be divided into two parts: 1, how to fetch data, 2 how to render HTML. Before either of them is done, we only get a router from the request, which is a string, and with some cookies or other header.
Problem 2 is easier, like said renderToString is already there. It can be easy. Just pass the data to the component as props, and render it. But it also can be hard based on which store library you use, might be a lot of spaghetti.
Problem 1 is somehow a bit stranger. As front-end developer, fetching data from database may lead to bad code. At least my code does, when I was trying server side rendering, actually my teammate did that for me, and that project was quite simple. After all backend developer are familiar with such tasks.
After both problems are solved, you need to make sure client renders first pages the same as that the server do. It's passing the same store to browsers with JSON, to help browsers initialise the same runtime.
My code is very obscure since I didn't use Redux github.com/jianliaoim/talk-os/tree/master/talk-ac… but the idea behind it is still clear.
ClojureScript Developer.
Stephan de Vries
Full stack developer, enthusiastic about new technologies.
React provides a
renderToString()method that renders all components and returns the output in HTML. On the server you can put this string inside of an HTML file and send it as a response.The tricky part though is to asynchronously fetch data for each of your components. Your state needs to be hydrated upon loading. Each component should specify what data it requires. On the server you then need to loop through these components and fetch that data. This works best with promises. As soon as you have fetched the necessary data on the server, you need to pass it to a global 'initial state' variable so that React can use that state and 'take over' the DOM.
I recommend checking out MERN, a 'Mongo, Express, React and Node' project by Hashnode that also does Server Side Rendering.