Server-Side Rendering
Learn how to fetch content from the server and render it in the frontend.
We'll cover the following...
We saw in the previous lesson that our application works and this is great news. However, the app is running only on the client side, which means that if we try to curl one of the pages, we’ll see something like this:
<!DOCTYPE html><html><head><meta charset="UTF-8"><title>My library</title></head><body><div id="root"></div><script type="text/javascript" src="/main.js"></script></body></html>
No content whatsoever! There’s only an empty container (the root div), which is where our application is mounted at runtime.
Rendering the content
In this section, we’ll modify our application to be able to render the content from the server as well.
Let’s start by adding fastify and esm to our project by using the following command:
Now, we can create our server application in the src/server.js module:
There’s a lot of code here, so let’s discuss the main concepts introduced here step by step:
-
Since we’re not going to use the webpack dev server, we need to return the full HTML code of the page from our server. Here, we’re defining the HTML template for all our pages using a function and a template literal. We’ll be passing the result of our server-rendered React application as
contentto this template to get the final HTML ...