TExcelTAD
Home › Express & NestJS › Templates & Server-Side Rendering

Templates & Server-Side Rendering

Not every Express app is a JSON API. Express can also produce complete HTML pages on the server — admin panels, emails, documentation sites, classic multi-page apps. This is server-side rendering (SSR): the browser receives finished HTML, which loads fast and is easy for search engines to index.

Template engines

A template engine fills placeholders in an HTML template with data. Express supports any engine through app.set('view engine', …) and res.render():

Engine Syntax sample Notes
EJS <h1><%= title %></h1> plain HTML + JavaScript tags
Pug h1= title indentation-based, very short
Handlebars (express-handlebars) <h1>{{title}}</h1> logic-less, layouts and partials
Nunjucks <h1>{{ title }}</h1> Jinja-like, template inheritance

Setting up EJS

bash · try it yourself
npm install ejs
added 15 packages, and audited 82 packages in 1s

found 0 vulnerabilities
js
// app.js
const path = require('node:path');
const express = require('express');

const app = express();
app.set('view engine', 'ejs');                       // file extension and engine
app.set('views', path.join(__dirname, 'views'));     // where templates live

app.get('/books', (req, res) => {
  res.render('books', { title: 'Reading list', books: [{ title: 'Dune', read: true }, { title: 'Kindred', read: false }] });
});
html
<!-- views/books.ejs -->
<!doctype html>
<html>
  <head><title><%= title %></title></head>
  <body>
    <h1><%= title %></h1>
    <ul>
      <% for (const book of books) { %>
        <li><%= book.title %><% if (book.read) { %> ✓<% } %></li>
      <% } %>
    </ul>
    <%- include('partials/footer') %>
  </body>
</html>
EJS tag Meaning
<%= value %> output, HTML-escaped
<%- value %> output raw (only for trusted HTML, e.g. includes)
<% code %> run JavaScript, output nothing
bash · try it yourself
curl http://localhost:3000/books
<!doctype html>
<html>
  <head><title>Reading list</title></head>
  <body>
    <h1>Reading list</h1>
    <ul>
        <li>Dune ✓</li>
        <li>Kindred</li>
    </ul>
    <footer>© Reading Club</footer>
  </body>
</html>

A template engine in 20 lines

app.engine(ext, fn) lets you register any function as an engine. Writing a tiny one shows what res.render really does: read the file, substitute values (escaping HTML!), and hand the result back:

node · try it yourself
const express = require('express');
const fs = require('node:fs');
const path = require('node:path');

const escapeHtml = (s) => String(s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);

const app = express();
app.engine('tpl', (filePath, data, callback) => {
  fs.readFile(filePath, 'utf8', (err, template) => {
    if (err) return callback(err);
    callback(null, template.replace(/\{\{\s*(\w+)\s*\}\}/g, (_, key) => escapeHtml(data[key] ?? '')));
  });
});
app.set('view engine', 'tpl');
app.set('views', path.join(__dirname, 'views'));

fs.mkdirSync(path.join(__dirname, 'views'), { recursive: true });
fs.writeFileSync(path.join(__dirname, 'views', 'greeting.tpl'), '<h1>Hello, {{ name }}!</h1><p>{{ note }}</p>');

app.get('/hello/:name', (req, res) => {
  res.render('greeting', { name: req.params.name, note: 'Rendered on the server' });
});

const server = app.listen(0, async () => {
  const base = `http://localhost:${server.address().port}/hello/`;
  for (const name of ['Ana', encodeURIComponent('<script>alert(1)</script>')]) {
    const res = await fetch(base + name);
    console.log(res.headers.get('content-type'), '|', await res.text());
  }
  server.close();
});
text/html; charset=utf-8 | <h1>Hello, Ana!</h1><p>Rendered on the server</p>
text/html; charset=utf-8 | <h1>Hello, &lt;script&gt;alert(1)&lt;/script&gt;!</h1><p>Rendered on the server</p>

The second request is an attempted XSS attack. Because the engine escapes every value, the script tag is displayed as text instead of being executed.

Note: Escaping is the single most important feature of a template engine. Only use raw output (<%- %>, {{{ }}}, | safe) for HTML you generated yourself.

Shared data with res.locals and app.locals

Object Lifetime Typical content
app.locals whole app site name, helper functions
res.locals one request current user, flash messages, CSRF token

Both are merged into every template's data automatically, so a layout can show "Logged in as Ana" without every route passing it.

js
app.locals.siteName = 'Reading Club';
app.use((req, res, next) => { res.locals.user = req.user ?? null; next(); });

Forms and the Post/Redirect/Get pattern

Classic SSR apps handle forms with express.urlencoded() and redirect after a successful POST, so refreshing the page doesn't resubmit the form:

js
app.post('/books', express.urlencoded(), (req, res) => {
  books.push({ title: req.body.title, read: false });
  res.redirect(303, '/books'); // 303 See Other: follow with a GET
});

SSR, SPA or both?

Approach Rendering Good for
Express + templates server builds HTML per request admin tools, content sites, emails, low JS
Express API + SPA (React/Vue/Angular) browser builds HTML from JSON rich interactive apps
Meta-frameworks (Next.js, Nuxt, Angular SSR) server and browser SEO + interactivity

Test yourself

What does res.render('books', data) do?

  1. Sends data as JSON
  2. Renders the books template with data and sends the HTML
  3. Redirects to /books
  4. Reads a book from disk

In EJS, which tag outputs a value with HTML escaping?

  1. <% value %>
  2. <%= value %>
  3. <%- value %>
  4. <%# value %>

Why redirect with 303 after handling a form POST?

  1. To make the response smaller
  2. So refreshing the page performs a GET instead of resubmitting the form
  3. Browsers require it
  4. To log the user out