Skip to content

Server-side rendering

Server-side rendering

Server-side Rendering happens when a webserver receives a request at a given route, immediately runs code which builds an HTML file, and then serves that file to the client. The rendering occurs on the server, and the client receives a rendered HTML file.

Advantages:

Disadvantages:

Example:

dist/index.html:

<html>
<head></head>
<body>
  <p>
    @my_token@
  </p>
</body>
</html>

server.js:

// Express server

app.get("/", (req, res) => {
  const htmlFilePath = path.resolve("./dist/index.html");
  
  fs.readFile(htmlFilePath, "utf8", (error, data) => {
    if (error) {
      console.error("Server error:", error);
      return res.status(500).send("Server error occurred.");
    }

    // HTML data can be manipulated as needed before it's sent to the client.
    data = data.replace("@my_token@", "Hello, world!"); 
     
    return res.send(data);
  });
});

app.listen(PORT, () => {
  console.log(`Server is listening on port ${PORT}`);
});

When / is requested, the resulting HTML data will be:

<html>
<head></head>
<body>
  <p>
    Hello, world!
  </p>
</body>
</html>