Caretaker Express · PostgreSQL · Cedar

Module 3 · Build real CRUD features

3.4 Paging, sorting and filtering

Build a list that pages with LIMIT and OFFSET, filters with parameterized WHERE clauses, and sorts through an allowlist, after watching a sort parameter turn into SQL injection.

≈ 60 min 22 steps 205 lines of code Replay verified

Starting point

/issues shows up to 50 issues, newest first, with no way to narrow the list.

Outcome

/issues?status=open&priority=high&building=10&sort=title&dir=asc&page=2 works: filters, a sortable table header, pagination with a total count, and links that keep the other settings. Unknown or malicious values fall back to safe defaults.

The problem

Filtering is easy to do safely: values go into $1 placeholders. Sorting is different. The column name in ORDER BY is part of the SQL text; PostgreSQL does not accept a placeholder there, because a placeholder can only stand for a value. So the tempting approach is to put the query parameter straight into the SQL. Let's do exactly that, briefly, to see why we must not.

Make listIssues accept a sort expression and use it directly:

Editsrc/models/issues.jsJavaScript
Remove the lines marked − and add the lines marked +. Unmarked lines stay as they are; they show you where the change goes.
export async function listIssues() {export async function listIssues({ sort = 'e.occurred_at DESC' } = {}) {  const { rows } = await query(    `SELECT ${ISSUE_COLUMNS}     FROM issues e     JOIN buildings s ON s.id = e.building_id     ORDER BY e.occurred_at DESC, e.id DESC     ORDER BY ${sort}     LIMIT 50`,  );  return rows;}
Show the whole src/models/issues.js after this change
import { query } from '../db.js'; const ISSUE_COLUMNS = `  e.id, e.building_id, s.name AS building_name, s.organisation_id,  e.title, e.description, e.priority, e.status,  e.occurred_at, e.created_at, e.updated_at`; export async function listIssues({ sort = 'e.occurred_at DESC' } = {}) {  const { rows } = await query(    `SELECT ${ISSUE_COLUMNS}     FROM issues e     JOIN buildings s ON s.id = e.building_id     ORDER BY ${sort}     LIMIT 50`,  );  return rows;} export async function listRecentIssuesForBuilding(buildingId, limit = 10) {  const { rows } = await query(    `SELECT ${ISSUE_COLUMNS}     FROM issues e     JOIN buildings s ON s.id = e.building_id     WHERE e.building_id = $1     ORDER BY e.occurred_at DESC, e.id DESC     LIMIT $2`,    [buildingId, limit],  );  return rows;} export async function findIssue(id) {  const { rows } = await query(    `SELECT ${ISSUE_COLUMNS}     FROM issues e     JOIN buildings s ON s.id = e.building_id     WHERE e.id = $1`,    [id],  );  return rows[0] ?? null;} export async function createIssue({ building_id, title, description, priority, occurred_at }) {  const { rows } = await query(    `INSERT INTO issues (building_id, title, description, priority, occurred_at)     VALUES ($1, $2, $3, $4, $5)     RETURNING id`,    [building_id, title, description, priority, occurred_at],  );  return rows[0];} export async function updateIssue(id, { building_id, title, description, priority, status, occurred_at }) {  const { rows } = await query(    `UPDATE issues     SET building_id = $2, title = $3, description = $4, priority = $5, status = $6, occurred_at = $7, updated_at = now()     WHERE id = $1     RETURNING id`,    [id, building_id, title, description, priority, status, occurred_at],  );  return rows[0] ?? null;} export async function deleteIssue(id) {  const { rowCount } = await query('DELETE FROM issues WHERE id = $1', [id]);  return rowCount === 1;}
Editsrc/routes/issues.jsJavaScript
Remove the lines marked − and add the lines marked +. Unmarked lines stay as they are; they show you where the change goes.
  const issues = await listIssues();  const issues = await listIssues({ sort: req.query.sort });
Show the whole src/routes/issues.js after this change
import express from 'express';import { listIssues, findIssue, createIssue, updateIssue, deleteIssue } from '../models/issues.js';import { listBuildings } from '../models/buildings.js';import { PG_ERRORS } from '../db.js';import { parseId } from '../lib/ids.js';import { cleanText } from '../lib/validation.js'; export const issuesRouter = express.Router(); export const PRIORITIES = ['low', 'medium', 'high', 'critical'];export const STATUSES = ['open', 'investigating', 'closed'];const FIVE_MINUTES = 5 * 60 * 1000; // <input type="datetime-local"> sends "2026-11-02T09:15" without a time zone. We treat it as UTC.function parseDateTimeLocal(value) {  if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/.test(value)) {    return null;  }  const date = new Date(`${value}:00Z`);  return Number.isNaN(date.getTime()) ? null : date;} // The reverse: a Date as "YYYY-MM-DDTHH:MM" in UTC, for the input's value attribute.function toDateTimeLocal(date) {  return new Date(date).toISOString().slice(0, 16);} function validateIssue(input, { editing }) {  const errors = {};  const title = cleanText(input.title, { min: 3, max: 200 });  const description = cleanText(input.description, { max: 2000 });  const buildingId = parseId(input.building_id);  const occurredAt = parseDateTimeLocal(input.occurred_at);  const status = editing ? input.status : 'open';  if (!title.ok) {    errors.title = 'Title must be between 3 and 200 characters.';  }  if (!description.ok) {    errors.description = 'Description must be at most 2000 characters.';  }  if (!PRIORITIES.includes(input.priority)) {    errors.priority = `Priority must be one of: ${PRIORITIES.join(', ')}.`;  }  if (buildingId === null) {    errors.building_id = 'Choose a building.';  }  if (!occurredAt) {    errors.occurred_at = 'Enter the date and time it happened (UTC).';  } else if (occurredAt.getTime() > Date.now() + FIVE_MINUTES) {    errors.occurred_at = 'That time is in the future.';  }  if (!STATUSES.includes(status)) {    errors.status = `Status must be one of: ${STATUSES.join(', ')}.`;  }  // values: what the form shows again. record: what we store.  const values = {    title: title.text,    description: description.text,    priority: input.priority,    building_id: buildingId,    status,    occurred_at: typeof input.occurred_at === 'string' ? input.occurred_at : '',  };  const record = { ...values, occurred_at: occurredAt };  return { errors, values, record };} async function renderIssueForm(res, status, { issue = null, values = {}, errors = {} } = {}) {  const buildings = await listBuildings();  res.status(status).render('issues/form', {    title: issue ? `Edit issue #${issue.id}` : 'Report an issue',    action: issue ? `/issues/${issue.id}/edit` : '/issues',    issue,    values,    errors,    buildings,    priorities: PRIORITIES,    statuses: STATUSES,  });} async function loadIssue(req, res) {  const id = parseId(req.params.id);  const issue = id === null ? null : await findIssue(id);  if (!issue) {    res.status(404).render('not-found', { title: 'Not found', path: req.originalUrl });    return null;  }  return issue;} issuesRouter.get('/', async (req, res) => {  const issues = await listIssues({ sort: req.query.sort });  res.render('issues/index', { title: 'Maintenance issues', issues });}); issuesRouter.get('/new', async (req, res) => {  await renderIssueForm(res, 200, { values: { occurred_at: toDateTimeLocal(new Date()) } });}); issuesRouter.post('/', async (req, res) => {  const { errors, values, record } = validateIssue(req.body ?? {}, { editing: false });  if (Object.keys(errors).length > 0) {    return renderIssueForm(res, 400, { values, errors });  }  let created;  try {    created = await createIssue(record);  } catch (err) {    if (err.code === PG_ERRORS.FOREIGN_KEY_VIOLATION) {      return renderIssueForm(res, 400, { values, errors: { building_id: 'Choose a building.' } });    }    throw err;  }  res.redirect(303, `/issues/${created.id}`);}); issuesRouter.get('/:id', async (req, res) => {  const issue = await loadIssue(req, res);  if (!issue) return;  res.render('issues/show', { title: issue.title, issue });}); issuesRouter.get('/:id/edit', async (req, res) => {  const issue = await loadIssue(req, res);  if (!issue) return;  await renderIssueForm(res, 200, { issue, values: { ...issue, occurred_at: toDateTimeLocal(issue.occurred_at) } });}); issuesRouter.post('/:id/edit', async (req, res) => {  const issue = await loadIssue(req, res);  if (!issue) return;  const { errors, values, record } = validateIssue(req.body ?? {}, { editing: true });  if (Object.keys(errors).length > 0) {    return renderIssueForm(res, 400, { issue, values, errors });  }  try {    await updateIssue(issue.id, record);  } catch (err) {    if (err.code === PG_ERRORS.FOREIGN_KEY_VIOLATION) {      return renderIssueForm(res, 400, { issue, values, errors: { building_id: 'Choose a building.' } });    }    throw err;  }  res.redirect(303, `/issues/${issue.id}`);}); issuesRouter.post('/:id/delete', async (req, res) => {  const issue = await loadIssue(req, res);  if (!issue) return;  await deleteIssue(issue.id);  res.redirect(303, '/issues');});
Server terminal (leave it running)caretaker/
LOG_SQL=1 npm run dev
> caretaker@1.0.0 dev
> node --env-file=.env --watch src/server.js

Caretaker listening on http://localhost:3000

It sorts by title, as intended:

Run and comparecaretaker/
curl -s "http://localhost:3000/issues?sort=title" | grep -m 3 -o 'href="/issues/[0-9]*">[^<]*'
href="/issues/108">Bins not collected (#108)
href="/issues/116">Bins not collected (#116)
href="/issues/124">Bins not collected (#124)

Now send SQL instead of a column name. %20 is a URL-encoded space:

Run and comparecaretaker/
curl -si "http://localhost:3000/issues?sort=(SELECT%201/0)" | head -1
HTTP/1.1 500 Internal Server Error
Server terminal output
> node --env-file=.env --watch src/server.js

Caretaker listening on http://localhost:3000
SQL 27ms SELECT e.id, e.building_id, s.name AS building_name, s.organisation_id, e.title, e.description, e.priority, e.status, e.occurred_at, e.created_at, e.updated_at FROM issues e JOIN buildings s ON s.id = e.building_id ORDER BY title LIMIT 50 []
GET /issues?sort=title -> 200 (47 ms)
error: division by zero
    at /Users/you/code/caretaker/node_modules/pg-pool/index.js:45:11
    at process.processTicksAndRejections (node:internal/process/task_queues:103:5)
    at async query (file:///Users/you/code/caretaker/src/db.js:16:18)
    at async listIssues (file:///Users/you/code/caretaker/src/models/issues.js:9:20)
    at async file:///Users/you/code/caretaker/src/routes/issues.js:93:18 {
  length: 65,
  severity: 'ERROR',
  code: '22012',
  detail: undefined,
  hint: undefined,
  position: undefined,
  internalPosition: undefined,
  internalQuery: undefined,
  where: undefined,
  schema: undefined,
  table: undefined,
  column: undefined,
  dataType: undefined,
  constraint: undefined,
  file: 'int.c',
  line: '870',
  routine: 'int4div'
}
GET /issues?sort=(SELECT%201/0) -> 500 (4 ms)

PostgreSQL executed our input: it tried to compute 1/0. Once a client can run SQL in the ORDER BY, it can ask yes/no questions about any data the app's database user can read, for example "does organisation 2's name start with H?", and read the answer from the order of the rows:

Run and comparecaretaker/
curl -s "http://localhost:3000/issues?sort=(CASE%20WHEN%20(SELECT%20name%20FROM%20organisations%20WHERE%20id=2)%20LIKE%20'H%25'%20THEN%20e.title%20ELSE%20e.id::text%20END)" | grep -m 1 -o 'href="/issues/[0-9]*">[^<]*'
href="/issues/108">Bins not collected (#108)

The first row is the alphabetically first title, so the answer was "yes". Repeat with other letters and you can read another tenant's data one character at a time. This is SQL injection without any quotes in the input.

Ctrl+C Stop the server in the server terminal.

Build it

1. An allowlist of sort columns

The fix is to never put client text into SQL. The client chooses a key from a fixed list; our code maps the key to SQL that we wrote. Replace the naive listIssues with the full version:

Editsrc/models/issues.jsJavaScript
Remove the lines marked − and add the lines marked +. Unmarked lines stay as they are; they show you where the change goes.
export async function listIssues({ sort = 'e.occurred_at DESC' } = {}) {// Sort keys a client may ask for. Keys come from the URL; the SQL is ours.export const ISSUE_SORTS = {  occurred_at: 'e.occurred_at',  title: 'e.title',  building: 's.name',  priority: "array_position(ARRAY['low', 'medium', 'high', 'critical'], e.priority)",  status: "array_position(ARRAY['open', 'investigating', 'closed'], e.status)",}; export async function listIssues({ page = 1, perPage = 10, sort = 'occurred_at', dir = 'desc', status = null, priority = null, buildingId = null } = {}) {  const where = [];  const params = [];  if (status) {    params.push(status);    where.push(`e.status = $${params.length}`);  }  if (priority) {    params.push(priority);    where.push(`e.priority = $${params.length}`);  }  if (buildingId) {    params.push(buildingId);    where.push(`e.building_id = $${params.length}`);  }  const whereSql = where.length > 0 ? `WHERE ${where.join(' AND ')}` : '';  const direction = dir === 'asc' ? 'ASC' : 'DESC';  const orderSql = `${ISSUE_SORTS[sort] ?? ISSUE_SORTS.occurred_at} ${direction}, e.id ${direction}`;   const countResult = await query(    `SELECT count(*)::int AS total FROM issues e JOIN buildings s ON s.id = e.building_id ${whereSql}`,    params,  );  const { rows } = await query(    `SELECT ${ISSUE_COLUMNS}     FROM issues e     JOIN buildings s ON s.id = e.building_id     ORDER BY ${sort}     LIMIT 50`,     ${whereSql}     ORDER BY ${orderSql}     LIMIT $${params.length + 1} OFFSET $${params.length + 2}`,    [...params, perPage, (page - 1) * perPage],  );  return rows;  return { issues: rows, total: countResult.rows[0].total };}
Show the whole src/models/issues.js after this change
import { query } from '../db.js'; const ISSUE_COLUMNS = `  e.id, e.building_id, s.name AS building_name, s.organisation_id,  e.title, e.description, e.priority, e.status,  e.occurred_at, e.created_at, e.updated_at`; // Sort keys a client may ask for. Keys come from the URL; the SQL is ours.export const ISSUE_SORTS = {  occurred_at: 'e.occurred_at',  title: 'e.title',  building: 's.name',  priority: "array_position(ARRAY['low', 'medium', 'high', 'critical'], e.priority)",  status: "array_position(ARRAY['open', 'investigating', 'closed'], e.status)",}; export async function listIssues({ page = 1, perPage = 10, sort = 'occurred_at', dir = 'desc', status = null, priority = null, buildingId = null } = {}) {  const where = [];  const params = [];  if (status) {    params.push(status);    where.push(`e.status = $${params.length}`);  }  if (priority) {    params.push(priority);    where.push(`e.priority = $${params.length}`);  }  if (buildingId) {    params.push(buildingId);    where.push(`e.building_id = $${params.length}`);  }  const whereSql = where.length > 0 ? `WHERE ${where.join(' AND ')}` : '';  const direction = dir === 'asc' ? 'ASC' : 'DESC';  const orderSql = `${ISSUE_SORTS[sort] ?? ISSUE_SORTS.occurred_at} ${direction}, e.id ${direction}`;   const countResult = await query(    `SELECT count(*)::int AS total FROM issues e JOIN buildings s ON s.id = e.building_id ${whereSql}`,    params,  );  const { rows } = await query(    `SELECT ${ISSUE_COLUMNS}     FROM issues e     JOIN buildings s ON s.id = e.building_id     ${whereSql}     ORDER BY ${orderSql}     LIMIT $${params.length + 1} OFFSET $${params.length + 2}`,    [...params, perPage, (page - 1) * perPage],  );  return { issues: rows, total: countResult.rows[0].total };} export async function listRecentIssuesForBuilding(buildingId, limit = 10) {  const { rows } = await query(    `SELECT ${ISSUE_COLUMNS}     FROM issues e     JOIN buildings s ON s.id = e.building_id     WHERE e.building_id = $1     ORDER BY e.occurred_at DESC, e.id DESC     LIMIT $2`,    [buildingId, limit],  );  return rows;} export async function findIssue(id) {  const { rows } = await query(    `SELECT ${ISSUE_COLUMNS}     FROM issues e     JOIN buildings s ON s.id = e.building_id     WHERE e.id = $1`,    [id],  );  return rows[0] ?? null;} export async function createIssue({ building_id, title, description, priority, occurred_at }) {  const { rows } = await query(    `INSERT INTO issues (building_id, title, description, priority, occurred_at)     VALUES ($1, $2, $3, $4, $5)     RETURNING id`,    [building_id, title, description, priority, occurred_at],  );  return rows[0];} export async function updateIssue(id, { building_id, title, description, priority, status, occurred_at }) {  const { rows } = await query(    `UPDATE issues     SET building_id = $2, title = $3, description = $4, priority = $5, status = $6, occurred_at = $7, updated_at = now()     WHERE id = $1     RETURNING id`,    [id, building_id, title, description, priority, status, occurred_at],  );  return rows[0] ?? null;} export async function deleteIssue(id) {  const { rowCount } = await query('DELETE FROM issues WHERE id = $1', [id]);  return rowCount === 1;}

Read it carefully, because Module 8 builds on it:

  • Filters append a value to params and a condition with the matching placeholder number. $${params.length} produces $1, $2, and so on. Every filter value still travels as a parameter.
  • The ORDER BY is assembled only from strings in ISSUE_SORTS and the two literal words ASC/DESC. If the key is unknown, ?? ISSUE_SORTS.occurred_at falls back to the default. Nothing the client sends can reach the SQL text.
  • Priority and status sort by meaning, not alphabetically: array_position turns 'high' into 3, so critical sorts after high.
  • e.id as a tie-breaker. Many issues can share a value (all open). Without a unique last sort key, PostgreSQL may return rows in a different order on each query, and paging could show a row twice or skip one.
  • LIMIT ... OFFSET ... returns one page. OFFSET (page - 1) * perPage skips the earlier pages. The count query uses the same WHERE and the same parameters, so the total always matches the filtered list.

2. Parse the query string in the route

req.query values are strings chosen by the client. Turn them into safe options, ignoring anything unexpected. Add this to src/routes/issues.js, above the routes:

Editsrc/routes/issues.jsJavaScript
Remove the lines marked − and add the lines marked +. Unmarked lines stay as they are; they show you where the change goes.
Change 1 of 3
const PER_PAGE = 10; // Converts the query string into list options. Invalid values become defaults.function parseListQuery(query) {  const page = parseId(query.page) ?? 1;  return {    page,    sort: Object.hasOwn(ISSUE_SORTS, query.sort) ? query.sort : 'occurred_at',    dir: query.dir === 'asc' ? 'asc' : 'desc',    status: STATUSES.includes(query.status) ? query.status : null,    priority: PRIORITIES.includes(query.priority) ? query.priority : null,    building: parseId(query.building),  };} // Builds a /issues URL from the current options plus overrides, dropping defaults.function listUrl(options, overrides = {}) {  const merged = { ...options, ...overrides };  const params = new URLSearchParams();  for (const [key, value] of Object.entries(merged)) {    const isDefault = value === null || (key === 'page' && value === 1) || (key === 'sort' && value === 'occurred_at') || (key === 'dir' && value === 'desc');    if (!isDefault) params.set(key, String(value));  }  const qs = params.toString();  return qs ? `/issues?${qs}` : '/issues';} async function loadIssue(req, res) {
Change 2 of 3
issuesRouter.get('/', async (req, res) => {  const issues = await listIssues({ sort: req.query.sort });  res.render('issues/index', { title: 'Maintenance issues', issues });  const options = parseListQuery(req.query);  const { issues, total } = await listIssues({ ...options, buildingId: options.building, perPage: PER_PAGE });  const buildings = await listBuildings();  res.render('issues/index', {    title: 'Maintenance issues',    issues,    total,    options,    buildings,    priorities: PRIORITIES,    statuses: STATUSES,    totalPages: Math.max(1, Math.ceil(total / PER_PAGE)),    listUrl: (overrides) => listUrl(options, overrides),  });});
Change 3 of 3
import { listIssues, findIssue, createIssue, updateIssue, deleteIssue } from '../models/issues.js';import { listIssues, findIssue, createIssue, updateIssue, deleteIssue, ISSUE_SORTS } from '../models/issues.js';
Show the whole src/routes/issues.js after this change
import express from 'express';import { listIssues, findIssue, createIssue, updateIssue, deleteIssue, ISSUE_SORTS } from '../models/issues.js';import { listBuildings } from '../models/buildings.js';import { PG_ERRORS } from '../db.js';import { parseId } from '../lib/ids.js';import { cleanText } from '../lib/validation.js'; export const issuesRouter = express.Router(); export const PRIORITIES = ['low', 'medium', 'high', 'critical'];export const STATUSES = ['open', 'investigating', 'closed'];const FIVE_MINUTES = 5 * 60 * 1000; // <input type="datetime-local"> sends "2026-11-02T09:15" without a time zone. We treat it as UTC.function parseDateTimeLocal(value) {  if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/.test(value)) {    return null;  }  const date = new Date(`${value}:00Z`);  return Number.isNaN(date.getTime()) ? null : date;} // The reverse: a Date as "YYYY-MM-DDTHH:MM" in UTC, for the input's value attribute.function toDateTimeLocal(date) {  return new Date(date).toISOString().slice(0, 16);} function validateIssue(input, { editing }) {  const errors = {};  const title = cleanText(input.title, { min: 3, max: 200 });  const description = cleanText(input.description, { max: 2000 });  const buildingId = parseId(input.building_id);  const occurredAt = parseDateTimeLocal(input.occurred_at);  const status = editing ? input.status : 'open';  if (!title.ok) {    errors.title = 'Title must be between 3 and 200 characters.';  }  if (!description.ok) {    errors.description = 'Description must be at most 2000 characters.';  }  if (!PRIORITIES.includes(input.priority)) {    errors.priority = `Priority must be one of: ${PRIORITIES.join(', ')}.`;  }  if (buildingId === null) {    errors.building_id = 'Choose a building.';  }  if (!occurredAt) {    errors.occurred_at = 'Enter the date and time it happened (UTC).';  } else if (occurredAt.getTime() > Date.now() + FIVE_MINUTES) {    errors.occurred_at = 'That time is in the future.';  }  if (!STATUSES.includes(status)) {    errors.status = `Status must be one of: ${STATUSES.join(', ')}.`;  }  // values: what the form shows again. record: what we store.  const values = {    title: title.text,    description: description.text,    priority: input.priority,    building_id: buildingId,    status,    occurred_at: typeof input.occurred_at === 'string' ? input.occurred_at : '',  };  const record = { ...values, occurred_at: occurredAt };  return { errors, values, record };} async function renderIssueForm(res, status, { issue = null, values = {}, errors = {} } = {}) {  const buildings = await listBuildings();  res.status(status).render('issues/form', {    title: issue ? `Edit issue #${issue.id}` : 'Report an issue',    action: issue ? `/issues/${issue.id}/edit` : '/issues',    issue,    values,    errors,    buildings,    priorities: PRIORITIES,    statuses: STATUSES,  });} const PER_PAGE = 10; // Converts the query string into list options. Invalid values become defaults.function parseListQuery(query) {  const page = parseId(query.page) ?? 1;  return {    page,    sort: Object.hasOwn(ISSUE_SORTS, query.sort) ? query.sort : 'occurred_at',    dir: query.dir === 'asc' ? 'asc' : 'desc',    status: STATUSES.includes(query.status) ? query.status : null,    priority: PRIORITIES.includes(query.priority) ? query.priority : null,    building: parseId(query.building),  };} // Builds a /issues URL from the current options plus overrides, dropping defaults.function listUrl(options, overrides = {}) {  const merged = { ...options, ...overrides };  const params = new URLSearchParams();  for (const [key, value] of Object.entries(merged)) {    const isDefault = value === null || (key === 'page' && value === 1) || (key === 'sort' && value === 'occurred_at') || (key === 'dir' && value === 'desc');    if (!isDefault) params.set(key, String(value));  }  const qs = params.toString();  return qs ? `/issues?${qs}` : '/issues';} async function loadIssue(req, res) {  const id = parseId(req.params.id);  const issue = id === null ? null : await findIssue(id);  if (!issue) {    res.status(404).render('not-found', { title: 'Not found', path: req.originalUrl });    return null;  }  return issue;} issuesRouter.get('/', async (req, res) => {  const options = parseListQuery(req.query);  const { issues, total } = await listIssues({ ...options, buildingId: options.building, perPage: PER_PAGE });  const buildings = await listBuildings();  res.render('issues/index', {    title: 'Maintenance issues',    issues,    total,    options,    buildings,    priorities: PRIORITIES,    statuses: STATUSES,    totalPages: Math.max(1, Math.ceil(total / PER_PAGE)),    listUrl: (overrides) => listUrl(options, overrides),  });}); issuesRouter.get('/new', async (req, res) => {  await renderIssueForm(res, 200, { values: { occurred_at: toDateTimeLocal(new Date()) } });}); issuesRouter.post('/', async (req, res) => {  const { errors, values, record } = validateIssue(req.body ?? {}, { editing: false });  if (Object.keys(errors).length > 0) {    return renderIssueForm(res, 400, { values, errors });  }  let created;  try {    created = await createIssue(record);  } catch (err) {    if (err.code === PG_ERRORS.FOREIGN_KEY_VIOLATION) {      return renderIssueForm(res, 400, { values, errors: { building_id: 'Choose a building.' } });    }    throw err;  }  res.redirect(303, `/issues/${created.id}`);}); issuesRouter.get('/:id', async (req, res) => {  const issue = await loadIssue(req, res);  if (!issue) return;  res.render('issues/show', { title: issue.title, issue });}); issuesRouter.get('/:id/edit', async (req, res) => {  const issue = await loadIssue(req, res);  if (!issue) return;  await renderIssueForm(res, 200, { issue, values: { ...issue, occurred_at: toDateTimeLocal(issue.occurred_at) } });}); issuesRouter.post('/:id/edit', async (req, res) => {  const issue = await loadIssue(req, res);  if (!issue) return;  const { errors, values, record } = validateIssue(req.body ?? {}, { editing: true });  if (Object.keys(errors).length > 0) {    return renderIssueForm(res, 400, { issue, values, errors });  }  try {    await updateIssue(issue.id, record);  } catch (err) {    if (err.code === PG_ERRORS.FOREIGN_KEY_VIOLATION) {      return renderIssueForm(res, 400, { issue, values, errors: { building_id: 'Choose a building.' } });    }    throw err;  }  res.redirect(303, `/issues/${issue.id}`);}); issuesRouter.post('/:id/delete', async (req, res) => {  const issue = await loadIssue(req, res);  if (!issue) return;  await deleteIssue(issue.id);  res.redirect(303, '/issues');});
  • Object.hasOwn(ISSUE_SORTS, query.sort) is the allowlist check. We use hasOwn rather than query.sort in ISSUE_SORTS, because in would also accept inherited keys such as toString.
  • A page of 0, -1 or abc fails parseId and becomes page 1.
  • listUrl is passed to the template as a function, so links can say "same list, but page 3" or "same list, sorted by title".

3. The list template

Replace views/issues/index.ejs:

Replace whole fileviews/issues/index.ejsEJS
Highlighted lines are new or changed (45).
<%- include('../partials/head') %><div class="page-header">  <h1>Maintenance issues</h1>  <a class="btn btn-primary" href="/issues/new">Report an issue</a></div> <form method="get" action="/issues" class="filters">  <label>Status    <select name="status">      <option value="">Any</option>      <% for (const s of statuses) { %><option value="<%= s %>"<%= options.status === s ? ' selected' : '' %>><%= s %></option><% } %>    </select>  </label>  <label>Priority    <select name="priority">      <option value="">Any</option>      <% for (const s of priorities) { %><option value="<%= s %>"<%= options.priority === s ? ' selected' : '' %>><%= s %></option><% } %>    </select>  </label>  <label>Building    <select name="building">      <option value="">Any</option>      <% for (const building of buildings) { %><option value="<%= building.id %>"<%= options.building === building.id ? ' selected' : '' %>><%= building.organisation_name %> · <%= building.name %></option><% } %>    </select>  </label>  <input type="hidden" name="sort" value="<%= options.sort %>">  <input type="hidden" name="dir" value="<%= options.dir %>">  <button type="submit" class="btn btn-small">Apply</button>  <a class="btn btn-small" href="/issues">Reset</a></form> <%  const columns = [['title', 'Title'], ['building', 'Building'], ['priority', 'Priority'], ['status', 'Status'], ['occurred_at', 'Occurred']];  const arrow = (key) => (options.sort === key ? (options.dir === 'asc' ? ' ▲' : ' ▼') : '');  const nextDir = (key) => (options.sort === key && options.dir === 'desc' ? 'asc' : 'desc');%><p class="muted"><%= total %> issue<%= total === 1 ? '' : 's' %></p><% if (issues.length === 0) { %>  <p class="empty">No issues match these filters.</p><% } else { %>  <table class="data">    <thead>      <tr>        <% for (const [key, label] of columns) { %>          <th><a href="<%= listUrl({ sort: key, dir: nextDir(key), page: 1 }) %>"><%= label %><%= arrow(key) %></a></th>        <% } %>      </tr>    </thead>    <tbody>      <% for (const issue of issues) { %>        <tr>          <td><a href="/issues/<%= issue.id %>"><%= issue.title %></a></td>          <td><%= issue.building_name %></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.occurred_at) %></td>        </tr>      <% } %>    </tbody>  </table><% } %> <nav class="pagination" aria-label="Pages">  <% if (options.page > 1) { %><a href="<%= listUrl({ page: options.page - 1 }) %>">← Previous</a><% } %>  <% for (let p = 1; p <= totalPages; p++) { %>    <% if (p === options.page) { %><span class="current" aria-current="page"><%= p %></span><% } else { %><a href="<%= listUrl({ page: p }) %>"><%= p %></a><% } %>  <% } %>  <% if (options.page < totalPages) { %><a href="<%= listUrl({ page: options.page + 1 }) %>">Next →</a><% } %></nav><%- include('../partials/foot') %>

The filter form uses method="get": the choices become part of the URL, so a filtered list can be bookmarked and shared, and reloading is harmless. The hidden sort and dir fields keep the current sort when you apply a filter.

Run and inspect

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

Caretaker listening on http://localhost:3000
localhost:3000/issues?status=open&sort=priority&dir=desc
Open issues sorted by priority, most urgent first, with filters and pages.
Open issues sorted by priority, most urgent first, with filters and pages.

The same two malicious URLs again:

Run and comparecaretaker/
curl -si "http://localhost:3000/issues?sort=(SELECT%201/0)" | head -1
HTTP/1.1 200 OK
Run and comparecaretaker/
curl -si "http://localhost:3000/issues?page=-5&status=';DROP%20TABLE%20buildings;--" | head -1
HTTP/1.1 200 OK

Both are ordinary 200 pages with default sorting. Look at the SQL that actually ran for a real filter:

Run and comparecaretaker/
curl -s "http://localhost:3000/issues?status=open&building=20&sort=title&dir=asc&page=2" > /dev/null
(no output)
Server terminal output
SQL 1ms SELECT e.id, e.building_id, s.name AS building_name, s.organisation_id, e.title, e.description, e.priority, e.status, e.occurred_at, e.created_at, e.updated_at FROM issues e JOIN buildings s ON s.id = e.building_id WHERE e.status = $1 AND e.building_id = $2 ORDER BY e.title ASC, e.id ASC LIMIT $3 OFFSET $4 ["open",20,10,10]
SQL 2ms SELECT s.id, s.name, s.organisation_id, o.name AS organisation_name FROM buildings s JOIN organisations o ON o.id = s.organisation_id ORDER BY o.name, s.name []
GET /issues?status=open&building=20&sort=title&dir=asc&page=2 -> 200 (5 ms)

The SQL text contains only our own fragments; open, 20, 10 and 10 arrive as parameters.

Experiment

Predict There are 30 issues and 10 per page. What does ?page=4 show, and what status code does it return?
Run and comparecaretaker/
curl -s "http://localhost:3000/issues?page=4" | grep -E "class=\"muted\"|No issues"
<p class="muted">30 issues</p>
  <p class="empty">No issues match these filters.</p>
Reveal Answer

200, a total of 30, and "No issues match these filters". OFFSET 30 simply returns no rows. That is acceptable for a page the user had to type. One subtle point: because the count and the page are two separate queries, an issue inserted between them could make the total off by one. For a list page that is fine; Module 8 discusses when it is not.

Ctrl+C Stop the server in the server terminal.

Checkpoint

Add tests for the list behaviour in a new file:

Create filetest/issue-list.test.jsJavaScript
import { test, before, after } from 'node:test';import assert from 'node:assert/strict';import request from 'supertest';import { app } from '../src/app.js';import { pool } from '../src/db.js';import { resetDatabase } from './helpers.js'; before(resetDatabase);after(() => pool.end()); // The issue ids linked from the table rows, in order.function issueIds(html) {  return [...html.matchAll(/<td><a href="\/issues\/(\d+)">/g)].map((m) => Number(m[1]));} test('the list pages 10 at a time and reports the total', async () => {  const first = await request(app).get('/issues');  assert.equal(issueIds(first.text).length, 10);  assert.match(first.text, /30 issues/);  const third = await request(app).get('/issues?page=3');  assert.equal(issueIds(third.text).length, 10);  const fourth = await request(app).get('/issues?page=4');  assert.equal(issueIds(fourth.text).length, 0);}); test('pages do not overlap', async () => {  const ids = [];  for (const page of [1, 2, 3]) ids.push(...issueIds((await request(app).get(`/issues?page=${page}`)).text));  assert.equal(new Set(ids).size, 30);}); test('filters combine with AND', async () => {  const res = await request(app).get('/issues?status=open&building=20');  const ids = issueIds(res.text);  assert.ok(ids.length > 0);  const { rows } = await pool.query('SELECT id FROM issues WHERE status = $1 AND building_id = $2', ['open', 20]);  assert.deepEqual(new Set(ids), new Set(rows.map((r) => r.id)));}); test('sorting by priority puts critical first when descending', async () => {  const res = await request(app).get('/issues?sort=priority&dir=desc');  assert.match(res.text, /<span class="badge sev-critical">/);  const firstBadge = res.text.match(/class="badge sev-(\w+)"/)[1];  assert.equal(firstBadge, 'critical');}); test('unknown sort keys and SQL in the query string are ignored', async () => {  for (const qs of ['sort=(SELECT%201/0)', 'sort=toString', 'dir=sideways', 'page=-1', 'status=%27%3B--', 'building=abc']) {    const res = await request(app).get(`/issues?${qs}`);    assert.equal(res.status, 200, qs);    assert.equal(issueIds(res.text).length, 10, qs);  }});
Run and comparecaretaker/
npm test

> caretaker@1.0.0 test
> node --env-file=.env.test --test --test-concurrency=1 --test-reporter=spec "test/**/*.test.js"

✔ a building can be created inside an organisation (62.196625ms)
✔ a duplicate building name in the same organisation is a field error (3.101333ms)
✔ the same building name is allowed in another organisation (8.830958ms)
✔ a building with issues cannot be deleted (22.902541ms)
✔ an empty building can be deleted (6.999208ms)
✔ an organisation with buildings cannot be deleted, an empty one can (13.695791ms)
✔ the list pages 10 at a time and reports the total (72.558667ms)
✔ pages do not overlap (10.295166ms)
✔ filters combine with AND (3.469333ms)
✔ sorting by priority puts critical first when descending (3.11925ms)
✔ unknown sort keys and SQL in the query string are ignored (17.832084ms)
✔ GET /issues lists issues from the database (63.907625ms)
✔ GET /issues/101 shows one issue with its building (3.037041ms)
✔ GET /issues/:id answers 404 for unknown or malformed ids (5.961875ms)
✔ POST /issues re-renders the form with errors (6.582792ms)
✔ POST /issues stores the issue and redirects to it (6.756125ms)
✔ POST /issues with a building that does not exist is a form error, not a 500 (10.578209ms)
✔ the stored row has the cleaned values and ignores a client-sent status (3.396666ms)
✔ an issue time in the future is rejected (1.961625ms)
✔ GET /issues/101/edit shows the current values (2.501541ms)
✔ POST /issues/:id/edit changes the status and updated_at (2.733ms)
✔ POST /issues/:id/delete removes the issue (3.935459ms)
✔ GET /organisations lists organisations with building counts (49.735958ms)
✔ GET /organisations/1 shows its buildings, not other organisations' buildings (3.28725ms)
✔ POST /organisations validates and creates (10.047125ms)
✔ POST /organisations/:id/edit renames the organisation (4.949875ms)
✔ unknown organisations are 404 (4.262291ms)
ℹ tests 27
ℹ suites 0
ℹ pass 27
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 796.572875
Run and comparecaretaker/
git add -A
git commit -m "Paging, sorting and filtering"
[main 7495a38] Paging, sorting and filtering
 4 files changed, 177 insertions(+), 9 deletions(-)
 create mode 100644 test/issue-list.test.js
Symptom bind message supplies 3 parameters, but prepared statement "" requires 2

The number of values in params does not match the highest $n in the SQL. Print the SQL with LOG_SQL=1 and count.

Symptom The same issue appears on two pages

The ORDER BY lacks a unique tie-breaker. Keep e.id as the last sort key.

Recap and next step

Values go into placeholders, including LIMIT and OFFSET. Identifiers such as sort columns cannot, so the client picks a key from an allowlist and our code supplies the SQL. Every option from the query string is parsed and falls back to a default. A stable tie-breaker keeps pages consistent, and the count uses the same filters as the page.

Next: inspections, which have a workflow with rules about which status can follow which, and our first multi-statement transaction in the app.