Skip to content

1. Fundamentals

Views in Express.js are template files used to generate dynamic HTML pages on the server before sending them to the browser. They allow you to:

  • Insert dynamic data into HTML (e.g., user names, blog posts)
  • Reuse HTML components (headers, footers, navbars)
  • Keep your code clean by separating logic from presentation

1. πŸ”§ Setting Up Views in Express

1.1 Choose a Templating Engine

Templating engines allow you to use dynamic code inside your HTML. Popular ones include:

  • EJS (Embedded JavaScript)
  • Pug (formerly Jade)
  • Handlebars

We’ll use EJS here.

2.2 Install EJS

Terminal window
npm install ejs

2.3 Configure Express to Use Views

const express = require('express');
const app = express();
// Set the view engine to ejs
app.set('view engine', 'ejs');
// Set the directory for view templates (optional if default is used)
app.set('views', './views');

1.4 Create a View File

views/index.ejs:

<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
</head>
<body>
<h1>Hello, <%= name %>!</h1>
</body>
</html>
Directory Structure
project/
β”œβ”€β”€ views/
β”‚ β”œβ”€β”€ index.ejs
β”‚ └── about.ejs
β”œβ”€β”€ public/
β”‚ └── style.css
β”œβ”€β”€ app.js

You can also use partials (reusable view components) and layout systems (with tools like express-ejs-layouts).

1.5 Render the View in a Route

app.get('/', (req, res) => {
res.render('index', {
title: 'Welcome Page',
name: 'Nadith'
});
});

When a user accesses /, Express will:

βœ… Find views/index.ejs
βœ… Fill in the <%= %> values
βœ… Send the resulting HTML to the browser

2. 🧠 Why Use Views?

FeatureBenefit
Dynamic pagesShow user-specific content (e.g., dashboards)
Template reuseCommon layouts (headers, footers) across pages
Cleaner codeSeparate logic (routes) from HTML (views)
Server-side renderingGood for SEO, and fast first-page loads

3. 🌍 Example with Route Params

app.get('/hello/:user', (req, res) => {
res.render('index', {
title: 'Hello Page',
name: req.params.user
});
});

Visit /hello/Alex β†’ β€œHello, Alex!”

πŸ§ͺ Summary

ConceptDescription
app.set('view engine', 'ejs')Sets templating engine
res.render('view', data)Renders the view and injects data
<%= %> in templateEmbeds dynamic data in HTML