agyanadda@gmail.com

Express.js Templates with EJS

Express.js and Databases 1 min read Updated Dec 3, 2026 Topic 18 of 30

To build server-rendered websites (not just APIs), Express uses a template engine. EJS (Embedded JavaScript) is simple because it is plain HTML with JavaScript tags.

Setup

npm install ejs, then app.set('view engine', 'ejs'). Templates go in the views folder with the .ejs extension.

Render a page

res.render('index', { title: 'Home', posts }) loads views/index.ejs with the data.

EJS tags

  • <%= value %> — print, escaped (safe against XSS)
  • <%- html %> — print raw HTML (trusted content only, or includes)
  • <% code %> — run JavaScript (loops, if) without printing

Partials

Reuse header and footer: <%- include('partials/header', { title }) %>.

Forms

A form posts to an Express route; read fields with req.body after express.urlencoded({ extended: true }), then res.redirect().

Other engines: Pug, Handlebars, Nunjucks. Many modern apps use React or Vue for the frontend and Express only for the API.

Example

Example — Posts page with EJS JavaScript
// app.js
import express from 'express';
const app = express();
app.set('view engine', 'ejs');
app.use(express.urlencoded({ extended: true }));

const posts = [{ title: 'Learn Node' }, { title: 'Learn Express' }];

app.get('/', (req, res) => res.render('index', { title: 'Blog', posts }));
app.post('/posts', (req, res) => {
  posts.push({ title: req.body.title });
  res.redirect('/');
});
app.listen(3000);

/* views/index.ejs
<%- include('partials/header', { title }) %>
<h1><%= title %></h1>
<% if (posts.length === 0) { %>
  <p>No posts yet.</p>
<% } %>
<ul>
  <% posts.forEach(post => { %>
    <li><%= post.title %></li>
  <% }) %>
</ul>
<form method="POST" action="/posts">
  <input name="title" required> <button>Add</button>
</form>
*/

The home page lists the posts. Submitting the form adds a post and redirects back to the list. A title like <b>hi</b> is shown as text because <%= %> escapes it.

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which EJS tag prints a value safely escaped?

Exercise 2 True / False

res.render('index') loads views/index.ejs when EJS is the view engine.

Exercise 3 Fill in the Blank

Insert a partial with <%- ___('partials/header') %>

Frequently Asked Questions

EJS is great for simple server-rendered sites, admin panels and SEO-friendly pages with little JavaScript. For highly interactive apps, use React or Vue for the frontend with Express as a JSON API.