Caretaker Express · PostgreSQL · Cedar

Module 1 · Our first Express application

1.4 HTML pages with EJS

Render real pages with EJS templates and shared partials, serve a stylesheet, accept an HTML form, redirect after a successful POST, and see why output escaping matters.

≈ 75 min 27 steps 242 lines of code Replay verified

Starting point

src/server.js serves a JSON API for issues: list, show, create, plus a logger, a 404 handler and an error handler. A browser user would have to read raw JSON.

Outcome

People can use Caretaker in a browser:

  • /issues lists issues in a table;
  • /issues/new shows a form; invalid input comes back with messages next to each field;
  • a successful submit redirects to the new issue's page;
  • unknown pages show a friendly HTML 404, while /api/... keeps answering JSON.
Text
caretaker/├── public/css/style.css├── src/server.js└── views/    ├── issues/  index.ejs  new.ejs  show.ejs    ├── partials/  head.ejs  nav.ejs  foot.ejs    ├── error.ejs    └── not-found.ejs

The problem

We could build HTML with template strings in JavaScript: res.send(`<h1>${issue.title}</h1>`). It works until an issue title contains <script>. Then the browser runs it. String-building HTML also mixes layout and logic in one file. A template engine solves both: templates hold the markup, and the engine escapes values by default.

Build it

1. Install EJS

EJS ("Embedded JavaScript") is close to plain HTML. It adds three tags:

Tag Meaning
<%= value %> Output value, HTML-escaped. Use this for data.
<%- html %> Output without escaping. Use it only for trusted HTML, such as an included template.
<% code %> Run JavaScript (loops, if) without output.
Run and comparecaretaker/
npm install ejs@7.0.2

added 1 package, and audited 67 packages in 738ms

31 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities

2. Tell Express where templates live

Add two imports at the top of src/server.js and configure the view engine right after creating the app:

Editsrc/server.jsJavaScript
Remove the lines marked − and add the lines marked +. Unmarked lines stay as they are; they show you where the change goes.
import express from 'express';import path from 'node:path'; const app = express();const port = 3000; app.set('view engine', 'ejs');app.set('views', path.join(import.meta.dirname, '..', 'views'));app.locals.formatDate = (iso) => new Date(iso).toLocaleString('en-IE', { dateStyle: 'medium', timeStyle: 'short', timeZone: 'UTC' });
Show the whole src/server.js after this change
import express from 'express';import path from 'node:path'; const app = express();const port = 3000; app.set('view engine', 'ejs');app.set('views', path.join(import.meta.dirname, '..', 'views'));app.locals.formatDate = (iso) => new Date(iso).toLocaleString('en-IE', { dateStyle: 'medium', timeStyle: 'short', timeZone: 'UTC' }); app.use((req, res, next) => {  const started = Date.now();  res.on('finish', () => {    console.log(`${req.method} ${req.originalUrl} -> ${res.statusCode} (${Date.now() - started} ms)`);  });  next();}); app.use(express.json()); const issues = [  { id: 1, title: 'Lift stuck between floors 2 and 3', priority: 'high', status: 'open', building: 'Dublin Offices', occurredAt: '2026-11-02T09:15:00.000Z' },  { id: 2, title: 'Dripping tap in the second-floor kitchen', priority: 'medium', status: 'closed', building: 'Dublin Offices', occurredAt: '2026-11-05T14:40:00.000Z' },  { id: 3, title: 'Front door lock sticks at entrance 4', priority: 'critical', status: 'open', building: 'Cork Apartments', occurredAt: '2026-11-08T07:05:00.000Z' },]; const PRIORITIES = ['low', 'medium', 'high', 'critical']; function validateIssue(input) {  const errors = {};  const title = typeof input.title === 'string' ? input.title.trim() : '';  const building = typeof input.building === 'string' ? input.building.trim() : '';  if (title.length < 3 || title.length > 200) {    errors.title = 'Title must be between 3 and 200 characters.';  }  if (!PRIORITIES.includes(input.priority)) {    errors.priority = `Priority must be one of: ${PRIORITIES.join(', ')}.`;  }  if (building.length === 0) {    errors.building = 'Building is required.';  }  return { errors, values: { title, priority: input.priority, building } };} app.get('/', (req, res) => {  res.send('Caretaker is running');}); app.get('/api/issues', (req, res) => {  const { status } = req.query;  const result = status ? issues.filter((issue) => issue.status === status) : issues;  res.json(result);}); app.get('/api/issues/:id', (req, res) => {  const id = Number(req.params.id);  const issue = issues.find((e) => e.id === id);  if (!issue) {    return res.status(404).json({ error: 'Issue not found' });  }  res.json(issue);}); let nextId = 4; app.post('/api/issues', (req, res) => {  const { errors, values } = validateIssue(req.body ?? {});  if (Object.keys(errors).length > 0) {    return res.status(400).json({ errors });  }  const issue = { id: nextId++, ...values, status: 'open', occurredAt: new Date().toISOString() };  issues.push(issue);  res.status(201).location(`/api/issues/${issue.id}`).json(issue);}); app.use((req, res) => {  res.status(404).json({ error: `No route for ${req.method} ${req.path}` });}); app.use((err, req, res, next) => {  const status = err.status ?? 500;  if (status >= 500) {    console.error(err);  }  res.status(status).json({ error: err.expose ? err.message : 'Something went wrong' });}); app.listen(port, () => {  console.log(`Caretaker listening on http://localhost:${port}`);});
  • app.set('view engine', 'ejs') means res.render('issues/index') looks for issues/index.ejs.
  • import.meta.dirname is the folder of the current module (src). We build an absolute path to views so the app works no matter which folder you start it from.
  • app.locals is an object whose properties every template can use. formatDate turns our ISO strings into a readable form. We fix the time zone to UTC so everyone sees the same output, including the course screenshots.

3. Shared page parts

Every page needs the same <head>, navigation and closing tags. We put them in partials and include them. Create the three files:

Create fileviews/partials/head.ejsEJS
<!doctype html><html lang="en"><head>  <meta charset="utf-8">  <meta name="viewport" content="width=device-width, initial-scale=1">  <title><%= title %> · Caretaker</title>  <link rel="stylesheet" href="/css/style.css"></head><body><%- include('nav') %><main class="container">
Create fileviews/partials/nav.ejsEJS
<header class="site-header">  <div class="container header-inner">    <a class="brand" href="/">Caretaker</a>    <nav class="main-nav" aria-label="Main">      <a href="/issues">Issues</a>    </nav>  </div></header>
Create fileviews/partials/foot.ejsEJS
</main><footer class="site-footer">  <div class="container">Caretaker · a learning application with synthetic data</div></footer></body></html>

include('nav') is resolved relative to the file that calls it, so head.ejs finds nav.ejs in the same folder. We use <%- because the included HTML is our own template, already escaped where needed.

4. The issues list page

Create fileviews/issues/index.ejsEJS
<%- include('../partials/head') %><div class="page-header">  <h1>Maintenance issues</h1>  <a class="btn btn-primary" href="/issues/new">Report an issue</a></div> <% if (issues.length === 0) { %>  <p class="empty">No issues yet.</p><% } else { %>  <table class="data">    <thead>      <tr><th>Title</th><th>Building</th><th>Priority</th><th>Status</th><th>Occurred</th></tr>    </thead>    <tbody>      <% for (const issue of issues) { %>        <tr>          <td><a href="/issues/<%= issue.id %>"><%= issue.title %></a></td>          <td><%= issue.building %></td>          <td><span class="badge sev-<%= issue.priority %>"><%= issue.priority %></span></td>          <td><span class="badge status-<%= issue.status %>"><%= issue.status %></span></td>          <td><%= formatDate(issue.occurredAt) %></td>        </tr>      <% } %>    </tbody>  </table><% } %><%- include('../partials/foot') %>

The template receives issues and title from the route. <% for ... { %> and <% } %> wrap repeated HTML in an ordinary JavaScript loop.

5. The form

Create fileviews/issues/new.ejsEJS
<%- include('../partials/head') %><h1>Report a maintenance issue</h1> <% if (Object.keys(errors).length > 0) { %>  <div class="error-summary" role="alert">    <p>Please fix the highlighted fields.</p>  </div><% } %> <form method="post" action="/issues" class="form" novalidate>  <div class="field<%= errors.title ? ' has-error' : '' %>">    <label for="title">Title</label>    <input id="title" name="title" value="<%= values.title ?? '' %>" maxlength="200" required>    <% if (errors.title) { %><p class="field-error"><%= errors.title %></p><% } %>  </div>   <div class="field<%= errors.building ? ' has-error' : '' %>">    <label for="building">Building</label>    <input id="building" name="building" value="<%= values.building ?? '' %>" required>    <% if (errors.building) { %><p class="field-error"><%= errors.building %></p><% } %>  </div>   <div class="field<%= errors.priority ? ' has-error' : '' %>">    <label for="priority">Priority</label>    <select id="priority" name="priority">      <option value="">Choose…</option>      <% for (const s of priorities) { %>        <option value="<%= s %>"<%= values.priority === s ? ' selected' : '' %>><%= s %></option>      <% } %>    </select>    <% if (errors.priority) { %><p class="field-error"><%= errors.priority %></p><% } %>  </div>   <div class="form-actions">    <button type="submit" class="btn btn-primary">Save issue</button>    <a class="btn" href="/issues">Cancel</a>  </div></form><%- include('../partials/foot') %>
  • method="post" and action="/issues": the browser sends a POST to /issues with the fields encoded as title=...&building=...&priority=... (application/x-www-form-urlencoded).
  • value="<%= values.title ?? '' %>" puts the user's input back after a validation error, so they do not retype it. It is escaped, so a " in the title cannot break out of the attribute.
  • novalidate turns off the browser's own checks so you can see the server validation working. The server must validate anyway: a browser check is a convenience, not a control.

6. The issue page, the 404 page and the error page

Create fileviews/issues/show.ejsEJS
<%- include('../partials/head') %><p class="breadcrumbs"><a href="/issues">Issues</a> / #<%= issue.id %></p><div class="page-header">  <h1><%= issue.title %></h1></div><dl class="details">  <dt>Building</dt><dd><%= issue.building %></dd>  <dt>Priority</dt><dd><span class="badge sev-<%= issue.priority %>"><%= issue.priority %></span></dd>  <dt>Status</dt><dd><span class="badge status-<%= issue.status %>"><%= issue.status %></span></dd>  <dt>Occurred</dt><dd><%= formatDate(issue.occurredAt) %></dd></dl><%- include('../partials/foot') %>
Create fileviews/not-found.ejsEJS
<%- include('partials/head') %><h1>Page not found</h1><p>We could not find <code><%= path %></code>.</p><p><a href="/issues">Go to the issues list</a></p><%- include('partials/foot') %>
Create fileviews/error.ejsEJS
<%- include('partials/head') %><h1><%= status === 500 ? 'Something went wrong' : 'Request failed' %></h1><p><%= message %></p><p><a href="/issues">Go to the issues list</a></p><%- include('partials/foot') %>

7. A stylesheet

Styling is not the subject of this course, so we write the whole stylesheet once, now, including classes that later lessons use (forms, flash messages, pagination, badges). Create public/css/style.css:

Create filepublic/css/style.cssCSS
:root {  --bg: #f6f7f9; --surface: #fff; --text: #1c2026; --muted: #646b75; --border: #dde1e6;  --accent: #1f56d1; --accent-dark: #1844a8; --danger: #b42318; --ok: #17784a; --warn: #9a5b00;  --radius: 8px; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Arial, sans-serif;}* { box-sizing: border-box; }body { margin: 0; background: var(--bg); color: var(--text); line-height: 1.5; font-size: 15px; }a { color: var(--accent); }code { font-family: ui-monospace, Menlo, monospace; font-size: .9em; }.container { max-width: 1080px; margin: 0 auto; padding: 0 20px; }main.container { padding-top: 28px; padding-bottom: 48px; min-height: calc(100vh - 140px); }.site-header { background: #14181f; color: #fff; }.header-inner { display: flex; align-items: center; gap: 24px; min-height: 56px; flex-wrap: wrap; }.brand { color: #fff; font-weight: 700; text-decoration: none; letter-spacing: -.01em; font-size: 17px; }.main-nav { display: flex; gap: 4px; flex: 1; flex-wrap: wrap; }.main-nav a { color: #c9d1dc; text-decoration: none; padding: 6px 10px; border-radius: 6px; }.main-nav a:hover { background: #262c36; color: #fff; }.user-nav { display: flex; align-items: center; gap: 10px; color: #c9d1dc; font-size: 14px; }.user-nav form { margin: 0; }.link-button { background: none; border: 0; color: #c9d1dc; cursor: pointer; font: inherit; padding: 6px 10px; border-radius: 6px; }.link-button:hover { background: #262c36; color: #fff; }.site-footer { color: var(--muted); font-size: 13px; padding: 20px 0 32px; }h1 { font-size: 26px; margin: 0 0 16px; letter-spacing: -.01em; }h2 { font-size: 19px; margin: 28px 0 12px; }.page-header { display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap; margin-bottom: 16px; }.page-header h1 { margin: 0; }.actions { display: flex; gap: 8px; flex-wrap: wrap; align-items: center; }.actions form { margin: 0; }.breadcrumbs { color: var(--muted); font-size: 14px; margin: 0 0 6px; }.btn { display: inline-block; padding: 8px 14px; border-radius: var(--radius); border: 1px solid var(--border); background: var(--surface); color: var(--text); text-decoration: none; font: inherit; font-weight: 550; cursor: pointer; }.btn:hover { border-color: #b9c0c9; }.btn-primary { background: var(--accent); border-color: var(--accent); color: #fff; }.btn-primary:hover { background: var(--accent-dark); }.btn-danger { color: var(--danger); border-color: #f0c7c3; }.btn-danger:hover { background: #fdecea; }.btn-small { padding: 4px 10px; font-size: 13px; }table.data { width: 100%; border-collapse: collapse; background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius); overflow: hidden; }table.data th, table.data td { padding: 10px 12px; text-align: left; border-bottom: 1px solid var(--border); vertical-align: top; }table.data th { background: #f0f2f5; font-size: 13px; color: #3c434d; font-weight: 600; }table.data th a { color: inherit; text-decoration: none; }table.data th a:hover { text-decoration: underline; }table.data tr:last-child td { border-bottom: 0; }.badge { display: inline-block; padding: 1px 8px; border-radius: 999px; font-size: 12.5px; font-weight: 600; background: #eceff3; color: #3c434d; white-space: nowrap; }.sev-low { background: #eef4ff; color: #2b4f99; }.sev-medium { background: #fff6dc; color: #7a5300; }.sev-high { background: #ffe9d6; color: #9a4100; }.sev-critical { background: #fde3e1; color: #a1170e; }.status-open, .status-submitted { background: #e7f0ff; color: #1d4ab3; }.status-investigating, .status-draft { background: #fff3d6; color: #7a5300; }.status-closed, .status-approved { background: #e5f5ec; color: #17653f; }.role-badge { background: #f1ecfb; color: #5b34a0; }.form { max-width: 560px; background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius); padding: 20px; }.field { margin-bottom: 16px; }.field label { display: block; font-weight: 600; margin-bottom: 4px; font-size: 14px; }.field input, .field select, .field textarea { width: 100%; padding: 8px 10px; border: 1px solid #c4cad2; border-radius: 6px; font: inherit; background: #fff; }.field textarea { min-height: 110px; resize: vertical; }.field.has-error input, .field.has-error select, .field.has-error textarea { border-color: var(--danger); }.field-error { color: var(--danger); font-size: 13.5px; margin: 4px 0 0; }.hint { color: var(--muted); font-size: 13px; margin: 4px 0 0; }.form-actions { display: flex; gap: 8px; }.error-summary { border: 1px solid #f0c7c3; background: #fdecea; color: #7f1d14; padding: 10px 14px; border-radius: var(--radius); margin-bottom: 16px; }.error-summary p { margin: 0; }.flash { padding: 10px 14px; border-radius: var(--radius); margin-bottom: 16px; border: 1px solid; }.flash-success { background: #e8f6ee; border-color: #b9e2c9; color: #155b37; }.flash-error { background: #fdecea; border-color: #f0c7c3; color: #7f1d14; }.details { display: grid; grid-template-columns: max-content 1fr; gap: 8px 20px; background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius); padding: 16px 20px; margin: 0 0 20px; }.details dt { color: var(--muted); font-weight: 600; font-size: 14px; }.details dd { margin: 0; }.prose { background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius); padding: 14px 20px; white-space: pre-wrap; margin: 0 0 20px; }.empty { color: var(--muted); background: var(--surface); border: 1px dashed var(--border); border-radius: var(--radius); padding: 24px; text-align: center; }.muted { color: var(--muted); }.filters { display: flex; gap: 10px; flex-wrap: wrap; align-items: flex-end; background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius); padding: 12px; margin-bottom: 14px; }.filters label { font-size: 12.5px; font-weight: 600; color: var(--muted); display: flex; flex-direction: column; gap: 3px; }.filters select, .filters input { padding: 6px 8px; border: 1px solid #c4cad2; border-radius: 6px; font: inherit; }.pagination { display: flex; gap: 6px; align-items: center; margin-top: 14px; flex-wrap: wrap; color: var(--muted); font-size: 14px; }.pagination a, .pagination span.current { padding: 4px 10px; border: 1px solid var(--border); border-radius: 6px; text-decoration: none; background: var(--surface); }.pagination span.current { background: var(--accent); border-color: var(--accent); color: #fff; }.cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 14px; margin-bottom: 24px; }.card { background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius); padding: 16px; }.card h3 { margin: 0 0 4px; font-size: 15px; }.card .stat { font-size: 28px; font-weight: 700; }.inline-form { display: inline; }@media (max-width: 640px) {  table.data { display: block; overflow-x: auto; }  .details { grid-template-columns: 1fr; }}

8. Routes that render pages

Now wire it together in src/server.js. First, serve files from public and parse HTML form bodies. Add both right after app.use(express.json());:

Editsrc/server.jsJavaScript
Remove the lines marked − and add the lines marked +. Unmarked lines stay as they are; they show you where the change goes.
app.use(express.static(path.join(import.meta.dirname, '..', 'public')));app.use(express.json());app.use(express.urlencoded({ extended: false }));
Show the whole src/server.js after this change
import express from 'express';import path from 'node:path'; const app = express();const port = 3000; app.set('view engine', 'ejs');app.set('views', path.join(import.meta.dirname, '..', 'views'));app.locals.formatDate = (iso) => new Date(iso).toLocaleString('en-IE', { dateStyle: 'medium', timeStyle: 'short', timeZone: 'UTC' }); app.use((req, res, next) => {  const started = Date.now();  res.on('finish', () => {    console.log(`${req.method} ${req.originalUrl} -> ${res.statusCode} (${Date.now() - started} ms)`);  });  next();}); app.use(express.static(path.join(import.meta.dirname, '..', 'public')));app.use(express.json());app.use(express.urlencoded({ extended: false })); const issues = [  { id: 1, title: 'Lift stuck between floors 2 and 3', priority: 'high', status: 'open', building: 'Dublin Offices', occurredAt: '2026-11-02T09:15:00.000Z' },  { id: 2, title: 'Dripping tap in the second-floor kitchen', priority: 'medium', status: 'closed', building: 'Dublin Offices', occurredAt: '2026-11-05T14:40:00.000Z' },  { id: 3, title: 'Front door lock sticks at entrance 4', priority: 'critical', status: 'open', building: 'Cork Apartments', occurredAt: '2026-11-08T07:05:00.000Z' },]; const PRIORITIES = ['low', 'medium', 'high', 'critical']; function validateIssue(input) {  const errors = {};  const title = typeof input.title === 'string' ? input.title.trim() : '';  const building = typeof input.building === 'string' ? input.building.trim() : '';  if (title.length < 3 || title.length > 200) {    errors.title = 'Title must be between 3 and 200 characters.';  }  if (!PRIORITIES.includes(input.priority)) {    errors.priority = `Priority must be one of: ${PRIORITIES.join(', ')}.`;  }  if (building.length === 0) {    errors.building = 'Building is required.';  }  return { errors, values: { title, priority: input.priority, building } };} app.get('/', (req, res) => {  res.send('Caretaker is running');}); app.get('/api/issues', (req, res) => {  const { status } = req.query;  const result = status ? issues.filter((issue) => issue.status === status) : issues;  res.json(result);}); app.get('/api/issues/:id', (req, res) => {  const id = Number(req.params.id);  const issue = issues.find((e) => e.id === id);  if (!issue) {    return res.status(404).json({ error: 'Issue not found' });  }  res.json(issue);}); let nextId = 4; app.post('/api/issues', (req, res) => {  const { errors, values } = validateIssue(req.body ?? {});  if (Object.keys(errors).length > 0) {    return res.status(400).json({ errors });  }  const issue = { id: nextId++, ...values, status: 'open', occurredAt: new Date().toISOString() };  issues.push(issue);  res.status(201).location(`/api/issues/${issue.id}`).json(issue);}); app.use((req, res) => {  res.status(404).json({ error: `No route for ${req.method} ${req.path}` });}); app.use((err, req, res, next) => {  const status = err.status ?? 500;  if (status >= 500) {    console.error(err);  }  res.status(status).json({ error: err.expose ? err.message : 'Something went wrong' });}); app.listen(port, () => {  console.log(`Caretaker listening on http://localhost:${port}`);});
  • express.static checks whether the URL matches a file in public. /css/style.css is served from public/css/style.css; anything else falls through to the next middleware.
  • express.urlencoded parses form posts into req.body. extended: false uses the simple parser, which produces flat string values. That is all an HTML form sends.

Next, replace the home route with a redirect, and add the page routes after the API routes:

Editsrc/server.jsJavaScript
Remove the lines marked − and add the lines marked +. Unmarked lines stay as they are; they show you where the change goes.
app.get('/', (req, res) => {  res.send('Caretaker is running');  res.redirect('/issues');});
Show the whole src/server.js after this change
import express from 'express';import path from 'node:path'; const app = express();const port = 3000; app.set('view engine', 'ejs');app.set('views', path.join(import.meta.dirname, '..', 'views'));app.locals.formatDate = (iso) => new Date(iso).toLocaleString('en-IE', { dateStyle: 'medium', timeStyle: 'short', timeZone: 'UTC' }); app.use((req, res, next) => {  const started = Date.now();  res.on('finish', () => {    console.log(`${req.method} ${req.originalUrl} -> ${res.statusCode} (${Date.now() - started} ms)`);  });  next();}); app.use(express.static(path.join(import.meta.dirname, '..', 'public')));app.use(express.json());app.use(express.urlencoded({ extended: false })); const issues = [  { id: 1, title: 'Lift stuck between floors 2 and 3', priority: 'high', status: 'open', building: 'Dublin Offices', occurredAt: '2026-11-02T09:15:00.000Z' },  { id: 2, title: 'Dripping tap in the second-floor kitchen', priority: 'medium', status: 'closed', building: 'Dublin Offices', occurredAt: '2026-11-05T14:40:00.000Z' },  { id: 3, title: 'Front door lock sticks at entrance 4', priority: 'critical', status: 'open', building: 'Cork Apartments', occurredAt: '2026-11-08T07:05:00.000Z' },]; const PRIORITIES = ['low', 'medium', 'high', 'critical']; function validateIssue(input) {  const errors = {};  const title = typeof input.title === 'string' ? input.title.trim() : '';  const building = typeof input.building === 'string' ? input.building.trim() : '';  if (title.length < 3 || title.length > 200) {    errors.title = 'Title must be between 3 and 200 characters.';  }  if (!PRIORITIES.includes(input.priority)) {    errors.priority = `Priority must be one of: ${PRIORITIES.join(', ')}.`;  }  if (building.length === 0) {    errors.building = 'Building is required.';  }  return { errors, values: { title, priority: input.priority, building } };} app.get('/', (req, res) => {  res.redirect('/issues');}); app.get('/api/issues', (req, res) => {  const { status } = req.query;  const result = status ? issues.filter((issue) => issue.status === status) : issues;  res.json(result);}); app.get('/api/issues/:id', (req, res) => {  const id = Number(req.params.id);  const issue = issues.find((e) => e.id === id);  if (!issue) {    return res.status(404).json({ error: 'Issue not found' });  }  res.json(issue);}); let nextId = 4; app.post('/api/issues', (req, res) => {  const { errors, values } = validateIssue(req.body ?? {});  if (Object.keys(errors).length > 0) {    return res.status(400).json({ errors });  }  const issue = { id: nextId++, ...values, status: 'open', occurredAt: new Date().toISOString() };  issues.push(issue);  res.status(201).location(`/api/issues/${issue.id}`).json(issue);}); app.use((req, res) => {  res.status(404).json({ error: `No route for ${req.method} ${req.path}` });}); app.use((err, req, res, next) => {  const status = err.status ?? 500;  if (status >= 500) {    console.error(err);  }  res.status(status).json({ error: err.expose ? err.message : 'Something went wrong' });}); app.listen(port, () => {  console.log(`Caretaker listening on http://localhost:${port}`);});
Editsrc/server.jsJavaScript
Remove the lines marked − and add the lines marked +. Unmarked lines stay as they are; they show you where the change goes.
  res.status(201).location(`/api/issues/${issue.id}`).json(issue);}); app.get('/issues', (req, res) => {  res.render('issues/index', { title: 'Maintenance issues', issues });}); app.get('/issues/new', (req, res) => {  res.render('issues/new', { title: 'Report an issue', values: {}, errors: {}, priorities: PRIORITIES });}); app.post('/issues', (req, res) => {  const { errors, values } = validateIssue(req.body ?? {});  if (Object.keys(errors).length > 0) {    return res.status(400).render('issues/new', { title: 'Report an issue', values, errors, priorities: PRIORITIES });  }  const issue = { id: nextId++, ...values, status: 'open', occurredAt: new Date().toISOString() };  issues.push(issue);  res.redirect(303, `/issues/${issue.id}`);}); app.get('/issues/:id', (req, res) => {  const issue = issues.find((e) => e.id === Number(req.params.id));  if (!issue) {    return res.status(404).render('not-found', { title: 'Not found', path: req.path });  }  res.render('issues/show', { title: issue.title, issue });});
Show the whole src/server.js after this change
import express from 'express';import path from 'node:path'; const app = express();const port = 3000; app.set('view engine', 'ejs');app.set('views', path.join(import.meta.dirname, '..', 'views'));app.locals.formatDate = (iso) => new Date(iso).toLocaleString('en-IE', { dateStyle: 'medium', timeStyle: 'short', timeZone: 'UTC' }); app.use((req, res, next) => {  const started = Date.now();  res.on('finish', () => {    console.log(`${req.method} ${req.originalUrl} -> ${res.statusCode} (${Date.now() - started} ms)`);  });  next();}); app.use(express.static(path.join(import.meta.dirname, '..', 'public')));app.use(express.json());app.use(express.urlencoded({ extended: false })); const issues = [  { id: 1, title: 'Lift stuck between floors 2 and 3', priority: 'high', status: 'open', building: 'Dublin Offices', occurredAt: '2026-11-02T09:15:00.000Z' },  { id: 2, title: 'Dripping tap in the second-floor kitchen', priority: 'medium', status: 'closed', building: 'Dublin Offices', occurredAt: '2026-11-05T14:40:00.000Z' },  { id: 3, title: 'Front door lock sticks at entrance 4', priority: 'critical', status: 'open', building: 'Cork Apartments', occurredAt: '2026-11-08T07:05:00.000Z' },]; const PRIORITIES = ['low', 'medium', 'high', 'critical']; function validateIssue(input) {  const errors = {};  const title = typeof input.title === 'string' ? input.title.trim() : '';  const building = typeof input.building === 'string' ? input.building.trim() : '';  if (title.length < 3 || title.length > 200) {    errors.title = 'Title must be between 3 and 200 characters.';  }  if (!PRIORITIES.includes(input.priority)) {    errors.priority = `Priority must be one of: ${PRIORITIES.join(', ')}.`;  }  if (building.length === 0) {    errors.building = 'Building is required.';  }  return { errors, values: { title, priority: input.priority, building } };} app.get('/', (req, res) => {  res.redirect('/issues');}); app.get('/api/issues', (req, res) => {  const { status } = req.query;  const result = status ? issues.filter((issue) => issue.status === status) : issues;  res.json(result);}); app.get('/api/issues/:id', (req, res) => {  const id = Number(req.params.id);  const issue = issues.find((e) => e.id === id);  if (!issue) {    return res.status(404).json({ error: 'Issue not found' });  }  res.json(issue);}); let nextId = 4; app.post('/api/issues', (req, res) => {  const { errors, values } = validateIssue(req.body ?? {});  if (Object.keys(errors).length > 0) {    return res.status(400).json({ errors });  }  const issue = { id: nextId++, ...values, status: 'open', occurredAt: new Date().toISOString() };  issues.push(issue);  res.status(201).location(`/api/issues/${issue.id}`).json(issue);}); app.get('/issues', (req, res) => {  res.render('issues/index', { title: 'Maintenance issues', issues });}); app.get('/issues/new', (req, res) => {  res.render('issues/new', { title: 'Report an issue', values: {}, errors: {}, priorities: PRIORITIES });}); app.post('/issues', (req, res) => {  const { errors, values } = validateIssue(req.body ?? {});  if (Object.keys(errors).length > 0) {    return res.status(400).render('issues/new', { title: 'Report an issue', values, errors, priorities: PRIORITIES });  }  const issue = { id: nextId++, ...values, status: 'open', occurredAt: new Date().toISOString() };  issues.push(issue);  res.redirect(303, `/issues/${issue.id}`);}); app.get('/issues/:id', (req, res) => {  const issue = issues.find((e) => e.id === Number(req.params.id));  if (!issue) {    return res.status(404).render('not-found', { title: 'Not found', path: req.path });  }  res.render('issues/show', { title: issue.title, issue });}); app.use((req, res) => {  res.status(404).json({ error: `No route for ${req.method} ${req.path}` });}); app.use((err, req, res, next) => {  const status = err.status ?? 500;  if (status >= 500) {    console.error(err);  }  res.status(status).json({ error: err.expose ? err.message : 'Something went wrong' });}); app.listen(port, () => {  console.log(`Caretaker listening on http://localhost:${port}`);});

Three details matter here:

  • Route order. /issues/new is registered before /issues/:id. Express tries routes in order, and :id would happily match the word new.
  • Redirect after POST. On success we answer 303 See Other with a Location header. The browser then GETs the issue page. If the user presses reload, the browser repeats that harmless GET instead of re-submitting the form. This pattern is called Post/Redirect/Get.
  • The same validateIssue. The JSON API and the HTML form share one validation function, so the rules cannot drift apart.

9. HTML for browsers, JSON for the API

Finally, make the 404 and error handlers answer in the right format. API paths keep JSON; every other path gets a page:

Editsrc/server.jsJavaScript
Remove the lines marked − and add the lines marked +. Unmarked lines stay as they are; they show you where the change goes.
app.use((req, res) => {  res.status(404).json({ error: `No route for ${req.method} ${req.path}` });  if (req.path.startsWith('/api/')) {    return res.status(404).json({ error: `No route for ${req.method} ${req.path}` });  }  res.status(404).render('not-found', { title: 'Not found', path: req.path });}); app.use((err, req, res, next) => {  const status = err.status ?? 500;  if (status >= 500) {    console.error(err);  }  res.status(status).json({ error: err.expose ? err.message : 'Something went wrong' });  const message = err.expose ? err.message : 'Something went wrong';  if (req.path.startsWith('/api/')) {    return res.status(status).json({ error: message });  }  res.status(status).render('error', { title: 'Error', status, message });});
Show the whole src/server.js after this change
import express from 'express';import path from 'node:path'; const app = express();const port = 3000; app.set('view engine', 'ejs');app.set('views', path.join(import.meta.dirname, '..', 'views'));app.locals.formatDate = (iso) => new Date(iso).toLocaleString('en-IE', { dateStyle: 'medium', timeStyle: 'short', timeZone: 'UTC' }); app.use((req, res, next) => {  const started = Date.now();  res.on('finish', () => {    console.log(`${req.method} ${req.originalUrl} -> ${res.statusCode} (${Date.now() - started} ms)`);  });  next();}); app.use(express.static(path.join(import.meta.dirname, '..', 'public')));app.use(express.json());app.use(express.urlencoded({ extended: false })); const issues = [  { id: 1, title: 'Lift stuck between floors 2 and 3', priority: 'high', status: 'open', building: 'Dublin Offices', occurredAt: '2026-11-02T09:15:00.000Z' },  { id: 2, title: 'Dripping tap in the second-floor kitchen', priority: 'medium', status: 'closed', building: 'Dublin Offices', occurredAt: '2026-11-05T14:40:00.000Z' },  { id: 3, title: 'Front door lock sticks at entrance 4', priority: 'critical', status: 'open', building: 'Cork Apartments', occurredAt: '2026-11-08T07:05:00.000Z' },]; const PRIORITIES = ['low', 'medium', 'high', 'critical']; function validateIssue(input) {  const errors = {};  const title = typeof input.title === 'string' ? input.title.trim() : '';  const building = typeof input.building === 'string' ? input.building.trim() : '';  if (title.length < 3 || title.length > 200) {    errors.title = 'Title must be between 3 and 200 characters.';  }  if (!PRIORITIES.includes(input.priority)) {    errors.priority = `Priority must be one of: ${PRIORITIES.join(', ')}.`;  }  if (building.length === 0) {    errors.building = 'Building is required.';  }  return { errors, values: { title, priority: input.priority, building } };} app.get('/', (req, res) => {  res.redirect('/issues');}); app.get('/api/issues', (req, res) => {  const { status } = req.query;  const result = status ? issues.filter((issue) => issue.status === status) : issues;  res.json(result);}); app.get('/api/issues/:id', (req, res) => {  const id = Number(req.params.id);  const issue = issues.find((e) => e.id === id);  if (!issue) {    return res.status(404).json({ error: 'Issue not found' });  }  res.json(issue);}); let nextId = 4; app.post('/api/issues', (req, res) => {  const { errors, values } = validateIssue(req.body ?? {});  if (Object.keys(errors).length > 0) {    return res.status(400).json({ errors });  }  const issue = { id: nextId++, ...values, status: 'open', occurredAt: new Date().toISOString() };  issues.push(issue);  res.status(201).location(`/api/issues/${issue.id}`).json(issue);}); app.get('/issues', (req, res) => {  res.render('issues/index', { title: 'Maintenance issues', issues });}); app.get('/issues/new', (req, res) => {  res.render('issues/new', { title: 'Report an issue', values: {}, errors: {}, priorities: PRIORITIES });}); app.post('/issues', (req, res) => {  const { errors, values } = validateIssue(req.body ?? {});  if (Object.keys(errors).length > 0) {    return res.status(400).render('issues/new', { title: 'Report an issue', values, errors, priorities: PRIORITIES });  }  const issue = { id: nextId++, ...values, status: 'open', occurredAt: new Date().toISOString() };  issues.push(issue);  res.redirect(303, `/issues/${issue.id}`);}); app.get('/issues/:id', (req, res) => {  const issue = issues.find((e) => e.id === Number(req.params.id));  if (!issue) {    return res.status(404).render('not-found', { title: 'Not found', path: req.path });  }  res.render('issues/show', { title: issue.title, issue });}); app.use((req, res) => {  if (req.path.startsWith('/api/')) {    return res.status(404).json({ error: `No route for ${req.method} ${req.path}` });  }  res.status(404).render('not-found', { title: 'Not found', path: req.path });}); app.use((err, req, res, next) => {  const status = err.status ?? 500;  if (status >= 500) {    console.error(err);  }  const message = err.expose ? err.message : 'Something went wrong';  if (req.path.startsWith('/api/')) {    return res.status(status).json({ error: message });  }  res.status(status).render('error', { title: 'Error', status, message });}); app.listen(port, () => {  console.log(`Caretaker listening on http://localhost:${port}`);});

Run and inspect

Server terminal (leave it running)caretaker/
npm run dev
> caretaker@1.0.0 dev
> node --watch src/server.js

Caretaker listening on http://localhost:3000

Open http://localhost:3000. The home page redirects to the list:

localhost:3000/issues
The issues list rendered by `views/issues/index.ejs`.
The issues list rendered by views/issues/index.ejs.

Look at the redirect with curl. -i shows that / answers 302 Found with Location: /issues; curl does not follow it unless you add -L:

Run and comparecaretaker/
curl -i http://localhost:3000/
HTTP/1.1 302 Found
X-Powered-By: Express
Location: /issues
Vary: Accept
Content-Type: text/plain; charset=utf-8
Content-Length: 29
Date: Sat, 28 Nov 2026 14:39:10 GMT
Connection: keep-alive
Keep-Alive: timeout=5

Found. Redirecting to /issues

Submit the form with empty fields. The server answers 400 and re-renders the form with messages:

localhost:3000/issues
Server-side validation: the short title is kept in the field, and each error appears next to its field.
Server-side validation: the short title is kept in the field, and each error appears next to its field.

Now fill it in correctly. The browser follows the 303 to the new issue's page:

localhost:3000/issues/4
After a successful POST the browser lands on /issues/4 (Post/Redirect/Get).
After a successful POST the browser lands on /issues/4 (Post/Redirect/Get).

The same form post with curl shows the raw 303 response. --data-urlencode encodes each field the way a browser form does:

Run and comparecaretaker/
curl -i http://localhost:3000/issues --data-urlencode "title=Water leak by the staff entrance" --data-urlencode "building=Dublin Offices" --data-urlencode "priority=low"
HTTP/1.1 303 See Other
X-Powered-By: Express
Location: /issues/5
Vary: Accept
Content-Type: text/plain; charset=utf-8
Content-Length: 35
Date: Sat, 28 Nov 2026 14:39:11 GMT
Connection: keep-alive
Keep-Alive: timeout=5

See Other. Redirecting to /issues/5

And a page that does not exist gets HTML, while the API still gets JSON:

Run and comparecaretaker/
curl -s http://localhost:3000/nowhere
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Not found · Caretaker</title>
  <link rel="stylesheet" href="/css/style.css">
</head>
<body>
<header class="site-header">
  <div class="container header-inner">
    <a class="brand" href="/">Caretaker</a>
    <nav class="main-nav" aria-label="Main">
      <a href="/issues">Issues</a>
    </nav>
  </div>
</header>

<main class="container">

<h1>Page not found</h1>
<p>We could not find <code>/nowhere</code>.</p>
<p><a href="/issues">Go to the issues list</a></p>
</main>
<footer class="site-footer">
  <div class="container">Caretaker · a learning application with synthetic data</div>
</footer>
</body>
</html>
Run and comparecaretaker/
curl -s http://localhost:3000/api/nowhere
{"error":"No route for GET /api/nowhere"}

Experiment

Submit an issue whose title is a piece of HTML.

Predict If the title is <script>alert("hi")</script>, what will the issues list page contain?
Run and comparecaretaker/
curl -i http://localhost:3000/issues --data-urlencode 'title=<script>alert("hi")</script>' --data-urlencode "building=Cork Apartments" --data-urlencode "priority=low"
HTTP/1.1 303 See Other
X-Powered-By: Express
Location: /issues/6
Vary: Accept
Content-Type: text/plain; charset=utf-8
Content-Length: 35
Date: Sat, 28 Nov 2026 14:39:11 GMT
Connection: keep-alive
Keep-Alive: timeout=5

See Other. Redirecting to /issues/6
Run and comparecaretaker/
curl -s http://localhost:3000/issues | grep -n "alert"
74:          <td><a href="/issues/6">&lt;script&gt;alert(&#34;hi&#34;)&lt;/script&gt;</a></td>
Reveal What you are seeing

EJS turned < into &lt;, > into &gt; and " into &#34;. The browser shows the text; it does not run it. This is output escaping, and it is why every data value in our templates uses <%= %>. If you change that one tag to <%- in index.ejs, the script runs in every visitor's browser: a stored cross-site scripting (XSS) bug. Do not leave such a change in place.

Ctrl+C Stop the server in the server terminal.

Checkpoint

Run and comparecaretaker/
git add -A
git commit -m "Render pages with EJS"
[main 6a98384] Render pages with EJS
 12 files changed, 256 insertions(+), 3 deletions(-)
 create mode 100644 public/css/style.css
 create mode 100644 views/error.ejs
 create mode 100644 views/issues/index.ejs
 create mode 100644 views/issues/new.ejs
 create mode 100644 views/issues/show.ejs
 create mode 100644 views/not-found.ejs
 create mode 100644 views/partials/foot.ejs
 create mode 100644 views/partials/head.ejs
 create mode 100644 views/partials/nav.ejs
Symptom Failed to lookup view "issues/index" in views directory

The views folder is in the wrong place, or the path is wrong. It must be caretaker/views, next to src, not inside it.

Symptom The page has no styling

Open http://localhost:3000/css/style.css. If it is a 404, the file is not at public/css/style.css, or express.static is registered after the 404 handler.

Symptom /issues/new shows "Page not found"

The /issues/:id route is registered before /issues/new, so new was treated as an ID. Move /issues/new above it.

Symptom ReferenceError: priorities is not defined in new.ejs

Every res.render('issues/new', ...) call must pass priorities. Check both the GET and the POST route.

Recap and next step

Templates hold markup; routes choose a template and pass data. Partials keep the shared layout in one place. <%= %> escapes output, which blocks script injection. Form posts arrive URL-encoded, are validated by the same function as the API, and successful posts redirect (Post/Redirect/Get).

Everything still lives in a JavaScript array. Next we write our first automated tests, and those tests will show us exactly why an array is not good enough.