Skip to content
Tutorials Center
My learning

Topics

Lesson 90 of 133 ยท Frameworks and Ecosystem

Template Engines: EJS and Server-Rendered Views

Learn how template engines such as EJS turn data into HTML, what res.render does, how escaping prevents XSS, and run a 25-line EJS-style engine with includes and layouts.

Not every Node.js server speaks JSON to a single-page app. Plenty of sites render HTML on the server: admin panels, dashboards, e-mail previews, documentation sites, and anything that must show real content to search engines on the first request. The usual tool is a template engine. You write an HTML file with holes in it, hand the engine some data, and it returns a finished page.

EJS ("Embedded JavaScript") is the simplest engine to learn because its templates are HTML with small pieces of plain JavaScript in <% %> tags. There is no new language to study. Pug, Handlebars and Nunjucks make other trade-offs, and we compare them at the end.

The ejs package cannot be installed in our editor, so this lesson shows the real Express setup read-only and then lets you run a tiny engine with the same tag syntax, including escaping, includes and layouts. Everything you learn about tags and escaping carries over to the real package.

The tags you need

Tag Meaning
<%= value %> Output the value, HTML-escaped
<%- value %> Output the value raw, unescaped
<% code %> Run JavaScript, output nothing (loops, conditions)
<%# note %> A comment
<%- include('partial', { ... }) %> Insert another template

That is nearly all of EJS. A loop is just a JavaScript for or forEach split across tags:

HTML
<ul>
  <% items.forEach((item) => { %>
    <li><%= item.name %></li>
  <% }) %>
</ul>

Using EJS in Express (read-only)

Terminal
npm install express ejs
JavaScript
import express from 'express';
import path from 'node:path';

const app = express();
app.set('view engine', 'ejs');                       // render() needs no file extension
app.set('views', path.join(import.meta.dirname, 'views'));

app.get('/', (req, res) => {
  res.render('home', { title: 'My shop', products: [{ name: 'Mug', price: 9 }] });
});

res.render('home', data) finds views/home.ejs, calls the engine with data, and sends the result as text/html. Express also merges app.locals (data for every view, such as the site name) and res.locals (data for this request, such as the logged-in user, usually set by middleware) into what the template sees. In production Express caches compiled templates when NODE_ENV=production; in development it re-reads the files on each request so edits show up immediately.

A tiny EJS-style engine you can run

An EJS-like engine is a small compiler. It turns a template into the source of a JavaScript function, where each piece of text becomes out += "..." and each tag becomes the matching code. Here it is in about 25 lines.

Node.js A 25-line template engine with EJS tags

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.

Look at the generated function at the bottom: there is no magic, only string concatenation. Two details to notice in the output. First, the title Shop & Co became Shop &amp; Co and the item Lamp <big> became Lamp &lt;big&gt;, because <%= escapes. Second, the blank lines come from the template's own line breaks around the scriptlet tags; real EJS has <%_ _%> and -%> tags to trim them, but whitespace never matters in HTML.

Escaping is your XSS defence

Rendering user input into a page without escaping lets an attacker inject a <script> that runs in other visitors' browsers (cross-site scripting, or XSS, covered in Web Application Security). <%= %> escapes the five characters that HTML treats specially, and this is the main reason to prefer a template engine over building HTML with template literals, where forgetting one escapeHtml() call is an invisible bug.

Use <%- only for HTML you produced and trust: the output of another include, or sanitized Markdown. Never for user input.

Escaping also depends on context. <%= %> is correct for text between tags and for quoted attributes. It is not enough inside a <script> block or a javascript: URL. To pass data to client-side code, serialize it with JSON.stringify and escape < as <, or put it in a data- attribute and read it from JavaScript.

Includes and layouts

Almost every page shares a header, a footer and a navigation bar. EJS solves this with include, and most projects add a layout: one template that wraps every page and receives the page's HTML as body. Plain EJS has no automatic layouts, so you either call include('header') and include('footer') at the top and bottom of each page, or render in two steps, which is what the example below does.

Node.js Views, a layout, and a tiny render() on a server

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 first page shows the layout wrapping the product list; each product is an include that receives { p }. The second request is the important one. The visitor's name is <script>steal()</script>. The <%= name %> line comes out harmless (&lt;script&gt;), while the deliberately wrong <%- name %> line would run the script in a real browser. Keep that contrast in mind each time you type a dash instead of an equals sign.

Structure of a server-rendered app

Server-rendered Express apps follow the layout from Project Structure and Architecture: route handlers stay thin, call a service to get data, and pass plain objects to a view.

  • Pass only what the view needs, not whole database rows (a password hash that is "just there" in an object is one typo from being printed).
  • Put shared data (the logged-in user, the CSRF token, flash messages) on res.locals in middleware.
  • Keep logic out of templates. A loop or an if is fine; a query or a calculation belongs in the handler.
  • Always send an error page for 404 and 500 through the same layout, so failures look like the rest of the site.

Other engines, and when to skip them all

  • Pug uses indentation instead of tags (ul then li= item.name). Short templates, but a new syntax to learn.
  • Handlebars and Mustache are "logic-less": {{name}} and {{#each items}}. Templates stay simple because they cannot run arbitrary code, which also makes them popular for e-mail and for templates that users can edit.
  • Nunjucks has inheritance ({% extends "layout.html" %} with blocks) and filters, the closest match to what Python developers know from Jinja2.
  • JSX on the server (React, Preact) and tagged template literals give you components and type checking, at the price of a build step.

If your front end is a single-page app, or you build a JSON API for mobile clients, you do not need a template engine at all. See REST APIs with Node.js. If you want mostly server-rendered pages with a bit of interactivity, EJS plus a few lines of browser JavaScript is a legitimate, very fast way to build.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the difference between <%= value %> and <%- value %> in EJS?

    The equals tag escapes the five special HTML characters so injected markup is shown as text. The dash tag prints the value untouched and is only safe for HTML you generated yourself.
  2. 2. What does res.render('home', { title: 'Hi' }) do in Express with EJS configured?

    render looks up the view, calls the engine with the data (plus app.locals and res.locals), and sends the produced HTML as the response.
  3. 3. Why is an XSS attack possible when a page prints user input with <%- ?

    Unescaped input such as <script>...</script> becomes real HTML in the page and runs with the site's privileges in other visitors' browsers.
  4. 4. Where should the logged-in user object normally be made available to every view?

    res.locals is merged into the data of every render for the current request, so one middleware can supply the user to all templates.

Summary

  • A template engine merges data into an HTML template; EJS uses plain JavaScript in <% %> tags.
  • <%= %> escapes (the default choice), <%- %> is raw, <% %> runs code, <%# %> is a comment.
  • res.render(view, data) renders views/<view>.ejs and sends HTML; app.locals and res.locals supply shared data.
  • An EJS-style engine compiles each template to a JavaScript function once, then calls it with data.
  • Escaping is the XSS defence, but it is context-dependent: scripts and URLs need extra care.
  • Use includes (and a layout wrapper) to share headers and footers; keep logic in handlers and services.

Next: Passport.js Strategies.