What is SSR?
SSR (Server-Side Rendering) is when HTML is generated on the server (not in the browser) and sent fully rendered to the client. It improves SEO and initial load speed."
This simple explanation is enough to get the idea.
In easy words — your page can be built on either:
- Client-side (CSR) → in the browser, or
- Server-side (SSR) → on the backend, using something like EJS.
Each has its pros and cons:
- SSR: Fast initial load, great SEO but not ideal for complex UIs
- CSR: Great for rich, dynamic UIs but poor SEO and slow first load
Many modern apps use a hybrid approach (e.g., Next.js). But for now, let’s stick to SSR with EJS.
Basic EJS Setup (Hello World)
Learn how to render a basic EJS template using Express.
Step 1: Initialize the Project
- Create a folder (name it whatever you want).
- Inside it:
npm init -y
npm install express ejs
- In
package.json
, add:
"type": "module"
(This is optional but needed to use import
instead of require
.)
Step 2: Create index.js
import express from "express";
import path from "path";
import { fileURLToPath } from "url";
const app = express();
const PORT = 3000;
// Required to get __dirname in ES modules
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// Set view engine
app.set("view engine", "ejs");
// Set views folder path explicitly
app.set("views", path.join(__dirname, "views"));
// Route
app.get("/", (req, res) => {
res.render("index", { name: "World" });
});
app.listen(PORT, () => {
console.log(`App listening at http://localhost:${PORT}`);
});
Step 3: Create Views Folder
Make a folder named views/
and inside it create a file:
views/index.ejs
<!DOCTYPE html>
<html>
<head>
<title>Hello EJS</title>
</head>
<body>
<h1>Hello, <%= name %>!</h1>
</body>
</html>
Why __dirname
is Needed?
In ES Modules, __dirname
and __filename
don’t exist by default like in CommonJS.
You need them to tell Express where to look for your EJS files (views).
Hence the use of:
import { fileURLToPath } from "url";
import path from "path";
.
Top comments (0)