Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 43 ยท Views and Templating

Template Engines and Server-Side Rendering

Render HTML pages on the server with Express: app.set views and view engine, res.render, locals, layouts, and a comparison of EJS, Pug and Handlebars.

So far our routes have sent text and JSON. Many sites, though, need to send HTML pages that change with the data: a product list, a profile, a blog post. Building HTML by gluing strings together gets messy and unsafe very quickly. A template engine lets you write the page as a template with holes in it, and fills the holes with data on every request. This is called server-side rendering (SSR): the server sends finished HTML, which is fast to show and easy for search engines to read.

The real Express and template-engine code is read-only here, because npm is not available in the browser. The runnable examples use our mini Express stand-in plus a small template renderer written for this lesson. Where it differs from the real engines, we say so.

How Express renders views

Express needs two settings and one method:

JavaScript
import express from 'express';
import path from 'node:path';

const app = express();

app.set('views', path.join(import.meta.dirname, 'views'));  // folder with templates
app.set('view engine', 'ejs');                               // default file extension + engine

app.get('/', (req, res) => {
  res.render('home', { title: 'Home', user: 'Mina' });       // views/home.ejs
});

res.render('home', data) finds views/home.ejs, passes it to the engine with your data, and sends the resulting HTML with a 200 status and Content-Type: text/html. If the file is missing or the template throws, Express calls next(err), so your error handler answers.

Express loads the engine package for you the first time (require('ejs') for 'ejs'). Some engines are not compatible with that automatic loading and need an explicit registration with app.engine():

JavaScript
import { engine } from 'express-handlebars';

app.engine('hbs', engine({ extname: '.hbs' }));
app.set('view engine', 'hbs');

Where data comes from

A template sees three sources, merged in this order (later wins):

  1. app.locals: values for every render, such as the site name.
  2. res.locals: values for this request, usually set by middleware (for example the signed-in user).
  3. The object you pass to res.render.
JavaScript
app.locals.siteName = 'Tutorial Shop';

app.use((req, res, next) => {
  res.locals.year = new Date().getFullYear();
  next();
});

Rendering step by step

Route runs It gathers data from services.
res.render Picks a template and passes data.
Engine Fills the holes, escapes text.
Response Finished HTML goes to the browser.

The browser never sees your template, only the result.

1 / 2

Comparing EJS, Pug and Handlebars

Express works with dozens of engines. Three are common:

Engine Looks like Strengths Watch out for
EJS HTML with <% %> tags of plain JavaScript Nothing new to learn if you know HTML and JS Logic can leak into templates
Pug Indented, no angle brackets Short; built-in extends and block layouts Whitespace-sensitive; syntax to learn
Handlebars HTML with {{ }} and a few helpers Intentionally limited logic; also runs in the browser Needs helpers for anything complex

The same list page in each, read-only:

HTML
<!-- EJS: views/list.ejs -->
<h1><%= title %></h1>
<ul>
  <% items.forEach(item => { %>
    <li><%= item.name %></li>
  <% }) %>
</ul>
PUG
//- Pug: views/list.pug
h1= title
ul
  each item in items
    li= item.name
HANDLEBARS
{{!-- Handlebars: views/list.hbs --}}
<h1>{{title}}</h1>
<ul>
  {{#each items}}
    <li>{{name}}</li>
  {{/each}}
</ul>

All three escape output by default (EJS <%= %>, Pug =, Handlebars {{ }}). Raw output exists too (<%- %>, !=, {{{ }}}), and you should use it only for HTML you built yourself.

For new projects, pick the engine your team finds easiest to read. Many teams choose EJS or Handlebars for familiarity, and some skip server templates entirely and use a front-end framework. This course teaches the Express side, which is identical for every engine.

Escaping: why it matters

If a user's name is <script>alert(1)</script> and you paste it into HTML as is, the browser runs it. This is cross-site scripting (XSS). An engine's escaping turns < into &lt; so the browser shows the text instead of running it.

Escape output by default and think twice before every raw tag (<%-, !=, {{{). Never mark user-provided text as raw.

A runnable template renderer

The renderer below is our own stand-in, not EJS or Handlebars. It supports {{ name }} (escaped), {{{ html }}} (raw), {{#each list}}...{{/each}} with {{this}}, and {{#if flag}}...{{/if}}. It processes the template in a single pass so inserted data is never treated as template code. It plays the role of an engine, and res.render is added by a middleware, the way Express wires it in.

Node.js res.render with a stand-in engine

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Compare the title and the third list item: <basket> and <b> come out as &lt;basket&gt; and &lt;b&gt;, because {{ }} escapes. The footer uses {{{ }}}, so its markup is kept. A missing view becomes an error that your error handler can catch, which matches how real Express behaves.

Layouts and partials

Most pages share a header and footer. There are two common approaches:

  • Partials: small template files you include from each page (<%- include('header') %> in EJS, {{> header}} in Handlebars).
  • Layouts: one outer template with a slot for the page content (Pug's extends/block, express-handlebars layouts, or express-ejs-layouts for EJS).

The stand-in below does layouts in the simplest possible way: render the page first, then render the layout with the page's HTML as the body value. It also shows app.locals and res.locals merging.

Node.js Layout, app.locals and res.locals

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The page title comes from the route, the site name from app.locals, and the user from res.locals. Notice the blurb: the text {{code}} is shown literally, because data is never re-scanned as template code.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which setting tells Express which engine to use when you call res.render('home')?

    'view engine' sets the default engine and file extension, so 'home' resolves to views/home.ejs.
  2. 2. Both app.locals and the data passed to res.render define "title". Which value does the template see?

    Data passed to res.render is merged last and wins over res.locals and app.locals.
  3. 3. What does <%= name %> do in EJS?

    <%= %> escapes HTML. Use <%- %> only for markup you trust.
  4. 4. Why can raw output of user text be dangerous?

    Unescaped text such as a script tag is executed by the browser.

Summary

  • Set views and view engine, then call res.render(name, data) to send server-rendered HTML.
  • Templates see app.locals, res.locals and the render data, with the render data winning.
  • EJS, Pug and Handlebars differ in syntax but all plug into the same Express API.
  • Escape by default; raw output is only for markup you created.
  • Layouts wrap page content, either through partials or an outer template with a body slot.

Next: Forms, Redirects and Flash Messages.