Node.js & Express

Template Engines with Express

18 min Lesson 10 of 40

Understanding Server-Side Rendering

So far, we've been sending JSON responses from our Express server. But what if you want to send full HTML pages dynamically? That's where template engines come in.

What is Server-Side Rendering (SSR)?

Server-Side Rendering is the process of generating HTML on the server and sending it to the client, rather than sending JavaScript that renders HTML in the browser.

SSR vs Client-Side Rendering:
  • SSR: Server generates HTML → Faster initial load, better SEO
  • CSR: Browser generates HTML from JavaScript → Better for interactive apps

What is a Template Engine?

A template engine allows you to write HTML with placeholders that get replaced with actual data at runtime. Think of it as HTML with superpowers.

EJS (Embedded JavaScript)

EJS is the most popular and beginner-friendly template engine. It uses plain HTML with embedded JavaScript.

Installing EJS

npm install ejs

Setting Up EJS in Express

const express = require('express'); const app = express(); // Set EJS as the template engine app.set('view engine', 'ejs'); // Set views directory app.set('views', './views'); app.get('/', (req, res) => { res.render('index', { title: 'Home Page' }); }); app.listen(3000);
Exercise: Build a Blog with EJS
  1. Set up Express with EJS
  2. Create home, post detail, and about pages
  3. Create partials for header and footer
  4. Style your pages with CSS
  5. Add a 404 page for invalid routes