Module 1 · Our first Express application
1.3 Middleware, JSON bodies and errors
Accept new issues with POST, learn what middleware is by writing one, validate input, and make errors safe and predictable.
Starting point
src/server.js has an in-memory issues array and three GET routes. We start the server with npm run dev.
Outcome
POST /api/issuescreates an issue and answers201 Createdwith aLocationheader.- Invalid input gets
400 Bad Requestand a list of field errors. - Every request is logged as
METHOD path -> status (ms)by a middleware you write. - Unknown routes get a JSON
404; unexpected failures get a generic500while the details stay in the server log.
The problem
Let's write the POST route the obvious way and see what happens. Add this above app.listen:
let nextId = 4; app.post('/api/issues', (req, res) => { const { title, priority, building } = req.body; const issue = { id: nextId++, title, priority, building, status: 'open', occurredAt: new Date().toISOString() }; issues.push(issue); res.status(201).json(issue);}); app.listen(port, () => {
Show the whole src/server.js after this change
import express from 'express'; const app = express();const port = 3000; 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' },]; 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 { title, priority, building } = req.body; const issue = { id: nextId++, title, priority, building, status: 'open', occurredAt: new Date().toISOString() }; issues.push(issue); res.status(201).json(issue);}); app.listen(port, () => { console.log(`Caretaker listening on http://localhost:${port}`);});import express from 'express';
const app = express();
const port = 3000;
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' },
];
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 { title, priority, building } = req.body;
const issue = { id: nextId++, title, priority, building, status: 'open', occurredAt: new Date().toISOString() };
issues.push(issue);
res.status(201).json(issue);
});
app.listen(port, () => {
console.log(`Caretaker listening on http://localhost:${port}`);
});
Start the server and send a JSON body. -d sends data and makes curl use POST; -H adds a header that tells the server the body is JSON:
npm run dev
> caretaker@1.0.0 dev
> node --watch src/server.js
Caretaker listening on http://localhost:3000
curl -i http://localhost:3000/api/issues -H "Content-Type: application/json" -d '{"title":"Broken light in stairwell B","priority":"low","building":"Cork Apartments"}'
HTTP/1.1 500 Internal Server Error
X-Powered-By: Express
Content-Security-Policy: default-src 'none'
X-Content-Type-Options: nosniff
Content-Type: text/html; charset=utf-8
Content-Length: 3107
Date: Sat, 28 Nov 2026 14:39:06 GMT
Connection: keep-alive
Keep-Alive: timeout=5
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>TypeError: Cannot destructure property 'title' of 'req.body' as it is undefined.<br> at file:///Users/you/code/caretaker/src/server.js:34:11<br> at Layer.handleRequest (/Users/you/code/caretaker/node_modules/router/lib/layer.js:169:33)<br> at next (/Users/you/code/caretaker/node_modules/router/lib/route.js:163:13)<br> at Route.dispatch (/Users/you/code/caretaker/node_modules/router/lib/route.js:123:3)<br> at handle (/Users/you/code/caretaker/node_modules/router/index.js:449:11)<br> at Layer.handleRequest (/Users/you/code/caretaker/node_modules/router/lib/layer.js:169:33)<br> at /Users/you/code/caretaker/node_modules/router/index.js:309:15<br> at processParams (/Users/you/code/caretaker/node_modules/router/index.js:619:12)<br> at next (/Users/you/code/caretaker/node_modules/router/index.js:305:5)<br> at Function.handle (/Users/you/code/caretaker/node_modules/router/index.js:187:3)</pre>
</body>
</html>
Two problems at once:
req.bodyisundefined. Express does not read request bodies by default. A body can be large, slow, or in many formats, so Express leaves that decision to you.- The error page contains a stack trace with file paths from your machine. That is useful while developing, but it tells an attacker how your code is laid out. We want a generic message for the client and the details in our log.
Build it
1. Middleware: functions that run before your routes
A middleware is a function (req, res, next). Express keeps a list of them in the order you call app.use(...) and routes (app.get, app.post) are in that same list. For each request Express walks the list from the top. Each middleware can:
- change
reqorres(for example, setreq.body); - end the request by sending a response;
- call
next()to pass control to the next item in the list.
Write one yourself first. Add a request logger directly after const app = express();:
const app = express();const port = 3000; 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();});
Show the whole src/server.js after this change
import express from 'express'; const app = express();const port = 3000; 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();}); 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' },]; 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 { title, priority, building } = req.body; const issue = { id: nextId++, title, priority, building, status: 'open', occurredAt: new Date().toISOString() }; issues.push(issue); res.status(201).json(issue);}); app.listen(port, () => { console.log(`Caretaker listening on http://localhost:${port}`);});import express from 'express';
const app = express();
const port = 3000;
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();
});
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' },
];
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 { title, priority, building } = req.body;
const issue = { id: nextId++, title, priority, building, status: 'open', occurredAt: new Date().toISOString() };
issues.push(issue);
res.status(201).json(issue);
});
app.listen(port, () => {
console.log(`Caretaker listening on http://localhost:${port}`);
});
res.on('finish', ...) registers a callback that runs after the response has been sent, so the log line knows the final status code. Then we call next() immediately; the logger never ends a request itself.
2. Parse JSON bodies
Express ships a body-parsing middleware: express.json(). Register it after the logger:
next();}); app.use(express.json());
Show the whole src/server.js after this change
import express from 'express'; const app = express();const port = 3000; 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' },]; 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 { title, priority, building } = req.body; const issue = { id: nextId++, title, priority, building, status: 'open', occurredAt: new Date().toISOString() }; issues.push(issue); res.status(201).json(issue);}); app.listen(port, () => { console.log(`Caretaker listening on http://localhost:${port}`);});import express from 'express';
const app = express();
const port = 3000;
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' },
];
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 { title, priority, building } = req.body;
const issue = { id: nextId++, title, priority, building, status: 'open', occurredAt: new Date().toISOString() };
issues.push(issue);
res.status(201).json(issue);
});
app.listen(port, () => {
console.log(`Caretaker listening on http://localhost:${port}`);
});
For requests with Content-Type: application/json, express.json() reads the body stream, parses it with JSON.parse, and stores the result in req.body. For any other content type it does nothing and req.body stays undefined. If the JSON is malformed it calls next(error) with a 400 error instead.
3. Validate before you store
The client controls every byte of the body. It can omit fields, send numbers instead of strings, or send a title that is ten megabytes long. Add a validation function above the routes, after the issues array:
{ 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 } };}
Show the whole src/server.js after this change
import express from 'express'; const app = express();const port = 3000; 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 { title, priority, building } = req.body; const issue = { id: nextId++, title, priority, building, status: 'open', occurredAt: new Date().toISOString() }; issues.push(issue); res.status(201).json(issue);}); app.listen(port, () => { console.log(`Caretaker listening on http://localhost:${port}`);});import express from 'express';
const app = express();
const port = 3000;
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 { title, priority, building } = req.body;
const issue = { id: nextId++, title, priority, building, status: 'open', occurredAt: new Date().toISOString() };
issues.push(issue);
res.status(201).json(issue);
});
app.listen(port, () => {
console.log(`Caretaker listening on http://localhost:${port}`);
});
typeof input.title === 'string'rejects numbers, arrays and objects. Without it,{"title": ["a","b","c"]}would pass a length check.errorsis an object keyed by field name. In the next lesson the HTML form shows each message next to its field.valuesholds the cleaned values. The route stores only these, neverreq.bodyitself, so an extra field such as"status": "closed"or"id": 1cannot sneak into the record.
Now use it in the route:
app.post('/api/issues', (req, res) => { const { title, priority, building } = req.body; const issue = { id: nextId++, title, priority, building, status: 'open', occurredAt: new Date().toISOString() }; 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).json(issue); res.status(201).location(`/api/issues/${issue.id}`).json(issue);});
Show the whole src/server.js after this change
import express from 'express'; const app = express();const port = 3000; 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.listen(port, () => { console.log(`Caretaker listening on http://localhost:${port}`);});import express from 'express';
const app = express();
const port = 3000;
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.listen(port, () => {
console.log(`Caretaker listening on http://localhost:${port}`);
});
req.body ?? {} handles a request without a JSON body. 201 Created is the status for "a new resource exists now", and the Location header says where it lives.
4. A 404 handler and an error handler
Two more pieces go after all routes, just above app.listen:
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' });});
Show the whole src/server.js after this change
import express from 'express'; const app = express();const port = 3000; 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}`);});import express from 'express';
const app = express();
const port = 3000;
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}`);
});
- The first is ordinary middleware. It runs only when nothing above it sent a response, so it is our "no route matched" handler.
- The second has four parameters. Express recognises an error handler by that count. It runs when anything earlier calls
next(err)or throws. Express 5 also catches errors thrown inasynchandlers and passes them here. - Errors from Express's own middleware carry
statusandexpose.exposeistruefor client errors such as malformed JSON, whose message is safe to show. For everything else the client getsSomething went wrong, and the full error goes toconsole.erroron the server.
Run and inspect
The server restarted when you saved. Send the same request as before:
curl -i http://localhost:3000/api/issues -H "Content-Type: application/json" -d '{"title":"Broken light in stairwell B","priority":"low","building":"Cork Apartments"}'
HTTP/1.1 201 Created
X-Powered-By: Express
Location: /api/issues/4
Content-Type: application/json; charset=utf-8
Content-Length: 148
ETag: W/"94-DBXbaDgAgNaORYmJJuRfV9Poy+k"
Date: Sat, 28 Nov 2026 14:39:07 GMT
Connection: keep-alive
Keep-Alive: timeout=5
{"id":4,"title":"Broken light in stairwell B","priority":"low","building":"Cork Apartments","status":"open","occurredAt":"2026-11-28T14:39:07.528Z"}
Look for HTTP/1.1 201 Created and Location: /api/issues/4. Follow the location:
curl -s http://localhost:3000/api/issues/4
{"id":4,"title":"Broken light in stairwell B","priority":"low","building":"Cork Apartments","status":"open","occurredAt":"2026-11-28T14:39:07.528Z"}
Now break the rules on purpose. A short title, an unknown priority and no building:
curl -i http://localhost:3000/api/issues -H "Content-Type: application/json" -d '{"title":"Hi","priority":"extreme"}'
HTTP/1.1 400 Bad Request
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 168
ETag: W/"a8-6JnFSb+j8TdTIUVAdfiiJv5de9I"
Date: Sat, 28 Nov 2026 14:39:07 GMT
Connection: keep-alive
Keep-Alive: timeout=5
{"errors":{"title":"Title must be between 3 and 200 characters.","priority":"Priority must be one of: low, medium, high, critical.","building":"Building is required."}}
Malformed JSON (note the missing closing brace):
curl -i http://localhost:3000/api/issues -H "Content-Type: application/json" -d '{"title":"oops"'
HTTP/1.1 400 Bad Request
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 94
ETag: W/"5e-OMkcaS9hWRf5rFEw68L+LhxdDHY"
Date: Sat, 28 Nov 2026 14:39:07 GMT
Connection: keep-alive
Keep-Alive: timeout=5
{"error":"Expected ',' or '}' after property value in JSON at position 15 (line 1 column 16)"}
The error message came from express.json() and was marked safe to show. A route that does not exist:
curl -s -X DELETE http://localhost:3000/api/issues/1
{"error":"No route for DELETE /api/issues/1"}
Now read the server terminal. Every request appears once, with its final status:
POST /api/issues -> 201 (10 ms)
GET /api/issues/4 -> 200 (1 ms)
POST /api/issues -> 400 (0 ms)
POST /api/issues -> 400 (1 ms)
DELETE /api/issues/1 -> 404 (0 ms)
Experiment
What does a crash inside an async route look like now? Add a temporary route that fails after a short wait, the way a database call might. Put it just above the 404 handler:
app.get('/api/boom', async (req, res) => { await new Promise((resolve) => setTimeout(resolve, 10)); throw new Error('Database password for db.internal is wrong');}); app.use((req, res) => { res.status(404).json({ error: `No route for ${req.method} ${req.path}` });});
Show the whole src/server.js after this change
import express from 'express'; const app = express();const port = 3000; 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.get('/api/boom', async (req, res) => { await new Promise((resolve) => setTimeout(resolve, 10)); throw new Error('Database password for db.internal is wrong');}); 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}`);});import express from 'express';
const app = express();
const port = 3000;
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.get('/api/boom', async (req, res) => {
await new Promise((resolve) => setTimeout(resolve, 10));
throw new Error('Database password for db.internal is wrong');
});
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}`);
});
curl -i http://localhost:3000/api/boom
HTTP/1.1 500 Internal Server Error
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 32
ETag: W/"20-cI8B1wZuBEyTE5ClDvphKZx7wd0"
Date: Sat, 28 Nov 2026 14:39:08 GMT
Connection: keep-alive
Keep-Alive: timeout=5
{"error":"Something went wrong"}
Caretaker listening on http://localhost:3000
Error: Database password for db.internal is wrong
at file:///Users/you/code/caretaker/src/server.js:73:9
GET /api/boom -> 500 (17 ms)
Reveal What happened
Express 5 noticed the rejected promise and passed the error to our error handler. The client got 500 and a generic message; the server log has the real message and the stack. Imagine that message contained a hostname or a password: that is exactly what must not reach the browser. (In Express 4 the same code would have left the request hanging, because Express 4 ignored rejected promises.)
Remove the experiment route:
app.get('/api/boom', async (req, res) => { await new Promise((resolve) => setTimeout(resolve, 10)); throw new Error('Database password for db.internal is wrong');}); app.use((req, res) => {
Show the whole src/server.js after this change
import express from 'express'; const app = express();const port = 3000; 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}`);});import express from 'express';
const app = express();
const port = 3000;
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}`);
});
Checkpoint
Order matters in Express. Check that your file has, from top to bottom: the logger, express.json(), the routes, the 404 handler, the error handler, then app.listen. Open "Show the whole src/server.js" under the last edit to compare.
git add -A
git commit -m "Accept new issues with validation and error handling"
[main 5778c36] Accept new issues with validation and error handling
1 file changed, 52 insertions(+)
Symptom The POST still returns 500 with Cannot destructure property
app.use(express.json()) is missing or is below the POST route. Middleware only affects routes registered after it.
Symptom 400 with Unexpected token for a request that looks right
Your shell changed the quotes. Wrap the JSON in single quotes, as in the examples. On Windows PowerShell quoting differs; use WSL.
Symptom The error handler never runs
It must have four parameters, (err, req, res, next), even if you do not use next, and it must be registered after the routes.
Recap and next step
Middleware is an ordered list of functions that see every request. You wrote one (the logger), used one (express.json()), and added the two that end the list: "not found" and "error". You validated input against an allowlist and stored only cleaned values. And you separated what the client sees from what the server logs.
Our API works with curl, but people will use a browser. Next we render HTML pages with EJS, accept form posts, and show validation errors next to the fields.
Open the checkpoint files for lesson 1.3 (separate page; only files from this lesson and earlier)