Server-Side Rendering (SSR) is a technique used to render web pages on the server and send the fully rendered HTML to the client. This can improve performance and SEO. This tutorial will guide you through the basics of SSR using a Node.js framework.
Prerequisites
- Node.js installed
- Basic knowledge of JavaScript and HTML
Getting Started
Create a new project: Initialize a new Node.js project by running
npm init
in your terminal and following the prompts.Install dependencies: Install a Node.js framework like Express to handle HTTP requests. Run
npm install express
to install it.Create server.js: Create a file named
server.js
and add the following code to set up a basic server.
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
- Start the server: Run
node server.js
in your terminal to start the server.
Implementing SSR
To implement SSR, we need to render the HTML on the server before sending it to the client. We can do this by using the render
method provided by the framework.
app.get('/en/tutorials/ssr', (req, res) => {
res.render('index', { title: 'Server-Side Rendering Tutorial' });
});
In this example, we are using a templating engine to render the HTML. You need to set up a view engine like EJS, Pug, or Handlebars. For this example, we will use EJS.
Install EJS: Run
npm install ejs
to install EJS.Set up EJS: Add the following line to your
server.js
file to set up EJS.
app.set('view engine', 'ejs');
- Create a view: Create a file named
index.ejs
in a folder namedviews
and add the following code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title><%= title %></title>
</head>
<body>
<h1><%= title %></h1>
<p>Welcome to the Server-Side Rendering tutorial!</p>
<a href="/en/tutorials/react">Read more about React</a>
</body>
</html>
- Run the server: Run
node server.js
in your terminal to start the server.
Conclusion
This tutorial provided a basic overview of Server-Side Rendering (SSR) using Node.js and Express. By following these steps, you should now have a basic SSR application running. For more information, check out our React tutorial.