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:
- Render dynamic data
- SEO. Websites arrive to the client as HTML, so web crawlers can easily read the website’s content.
Disadvantages:
- Complex to implement effectively
- Server overhead
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>