Express Exercises
Time to practise. Each exercise has a starter playground that already runs: it starts an app on a random port, sends a few requests and prints the results. Right now the TODO parts return placeholder answers — replace them so the output matches the Expected lines. Try first, then compare with the solution.
Note:
nodeexamples are simulated on this site. To check your solution for real, save it asex.jsin a folder where you rannpm install express, and runnode ex.js.
| # | Exercise | Topics |
|---|---|---|
| 1 | Multilingual greeting | route params, query strings |
| 2 | Request counter | middleware, headers |
| 3 | Sum endpoint | express.json(), validation, 400 |
| 4 | Central error handler | HttpError, async errors |
| 5 | Products router | express.Router, mounting |
| 6 | Paginated letters | pagination, meta |
| 7 | API key guard | auth middleware, 401/403 |
| 8 | Method not allowed | app.route, 405 + Allow |
1. Multilingual greeting
GET /greet/:name?lang=xx should answer { "message": "<greeting>, <name>!" }. Support en (Hello, the default), es (Hola) and fr (Bonjour). Unknown languages → 400 { "error": "unsupported language" }.
Expected:
200 {"message":"Hello, Ana!"}
200 {"message":"Hola, Ana!"}
200 {"message":"Bonjour, Léa!"}
400 {"error":"unsupported language"}const express = require('express');
const app = express();
app.get('/greet/:name', (req, res) => {
// TODO: read req.params.name and req.query.lang
res.json({ message: 'TODO' });
});
const server = app.listen(0, async () => {
const base = `http://localhost:${server.address().port}`;
for (const p of ['/greet/Ana', '/greet/Ana?lang=es', '/greet/L%C3%A9a?lang=fr', '/greet/Ana?lang=xx']) {
const res = await fetch(base + p);
console.log(res.status, await res.text());
}
server.close();
});200 {"message":"TODO"}
200 {"message":"TODO"}
200 {"message":"TODO"}
200 {"message":"TODO"}
Show solution
const GREETINGS = { en: 'Hello', es: 'Hola', fr: 'Bonjour' };
app.get('/greet/:name', (req, res) => {
const lang = req.query.lang ?? 'en';
const greeting = GREETINGS[lang];
if (!greeting) return res.status(400).json({ error: 'unsupported language' });
res.json({ message: `${greeting}, ${req.params.name}!` });
});Route parameters are already URL-decoded, so L%C3%A9a arrives as Léa. Note the return before the 400 response.
2. Request counter
Write a middleware that counts all requests the app has received and sets the header X-Request-Count on every response — including 404s. GET / returns { ok: true }.
Expected:
200 1
404 2
200 3const express = require('express');
const app = express();
// TODO: add a counting middleware here
app.get('/', (req, res) => res.json({ ok: true }));
const server = app.listen(0, async () => {
const base = `http://localhost:${server.address().port}`;
for (const p of ['/', '/nope', '/']) {
const res = await fetch(base + p);
console.log(res.status, res.headers.get('x-request-count'));
}
server.close();
});200 null
404 null
200 null
Show solution
let count = 0;
app.use((req, res, next) => {
count++;
res.set('X-Request-Count', String(count));
next();
});It must be registered before the routes; the 404 still gets the header because the middleware ran before Express's final handler.
3. Sum endpoint
POST /sum receives { "numbers": [ … ] } and answers { "sum": … }. If numbers is missing, not an array, or contains anything that isn't a finite number, answer 400 { "error": "numbers must be an array of numbers" }.
Expected:
200 {"sum":10}
200 {"sum":0}
400 {"error":"numbers must be an array of numbers"}
400 {"error":"numbers must be an array of numbers"}const express = require('express');
const app = express();
app.post('/sum', (req, res) => {
// TODO: parse the body, validate, sum
res.json({ sum: 0 });
});
const server = app.listen(0, async () => {
const url = `http://localhost:${server.address().port}/sum`;
for (const body of [{ numbers: [1, 2, 3, 4] }, { numbers: [] }, { numbers: [1, '2'] }, {}]) {
const res = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
console.log(res.status, await res.text());
}
server.close();
});200 {"sum":0}
200 {"sum":0}
200 {"sum":0}
200 {"sum":0}
Show solution
app.use(express.json());
app.post('/sum', (req, res) => {
const numbers = req.body?.numbers;
const valid = Array.isArray(numbers) && numbers.every((n) => typeof n === 'number' && Number.isFinite(n));
if (!valid) return res.status(400).json({ error: 'numbers must be an array of numbers' });
res.json({ sum: numbers.reduce((a, b) => a + b, 0) });
});Without express.json(), req.body is undefined — the optional chaining req.body?.numbers keeps that from crashing.
4. Central error handler
The async route throws HttpErrors. Finish the error-handling middleware so it replies with err.status and { error: err.message } for HttpErrors, and 500 { error: "Internal Server Error" } for anything else.
Expected:
200 {"id":1,"name":"Ana"}
404 {"error":"user 5 not found"}
500 {"error":"Internal Server Error"}const express = require('express');
class HttpError extends Error {
constructor(status, message) { super(message); this.status = status; }
}
const db = { async findUser(id) { return id === 1 ? { id: 1, name: 'Ana' } : null; } };
const app = express();
app.get('/users/:id', async (req, res) => {
const user = await db.findUser(Number(req.params.id));
if (!user) throw new HttpError(404, `user ${req.params.id} not found`);
res.json(user);
});
app.get('/bug', async () => { throw new TypeError('oops'); });
app.use((err, req, res, next) => {
// TODO: err.status + { error: err.message } for HttpError, 500 + generic message otherwise
res.status(500).send('TODO');
});
const server = app.listen(0, async () => {
const base = `http://localhost:${server.address().port}`;
for (const p of ['/users/1', '/users/5', '/bug']) {
const res = await fetch(base + p);
console.log(res.status, await res.text());
}
server.close();
});200 {"id":1,"name":"Ana"}
500 TODO
500 TODO
Show solution
app.use((err, req, res, next) => {
if (err instanceof HttpError) return res.status(err.status).json({ error: err.message });
res.status(500).json({ error: 'Internal Server Error' });
});Express 5 forwards the rejected promises of the async handlers to this middleware automatically. It needs all four parameters to be recognised as an error handler.
5. Products router
Move the product routes into a router and mount it at /api/products. GET /api/products lists names; GET /api/products/:id returns one product or 404 { "error": "not found" }.
Expected:
200 ["Pen","Ink"]
200 {"id":2,"name":"Ink"}
404 {"error":"not found"}const express = require('express');
const products = [{ id: 1, name: 'Pen' }, { id: 2, name: 'Ink' }];
const router = express.Router();
// TODO: router.get('/') and router.get('/:id')
const app = express();
// TODO: mount the router
const server = app.listen(0, async () => {
const base = `http://localhost:${server.address().port}`;
for (const p of ['/api/products', '/api/products/2', '/api/products/9']) {
const res = await fetch(base + p);
console.log(res.status, res.status === 404 && !(res.headers.get('content-type') ?? '').includes('json') ? '(no route yet)' : await res.text());
}
server.close();
});404 (no route yet)
404 (no route yet)
404 (no route yet)
Show solution
router.get('/', (req, res) => res.json(products.map((p) => p.name)));
router.get('/:id', (req, res) => {
const product = products.find((p) => p.id === Number(req.params.id));
if (!product) return res.status(404).json({ error: 'not found' });
res.json(product);
});
const app = express();
app.use('/api/products', router);Inside the router the paths are relative (/ and /:id); the prefix comes from app.use.
6. Paginated letters
GET /letters?page=&limit= pages through the 10 letters a–j. Defaults: page 1, limit 3; clamp limit to 1–5 and page to at least 1. Respond with { data, meta: { page, limit, total, pages } }.
Expected:
{"data":["a","b","c"],"meta":{"page":1,"limit":3,"total":10,"pages":4}}
{"data":["j"],"meta":{"page":4,"limit":3,"total":10,"pages":4}}
{"data":["f","g","h","i","j"],"meta":{"page":2,"limit":5,"total":10,"pages":2}}
{"data":["a"],"meta":{"page":1,"limit":1,"total":10,"pages":10}}const express = require('express');
const letters = 'abcdefghij'.split('');
const app = express();
app.get('/letters', (req, res) => {
// TODO: read and clamp page/limit, slice, compute meta
res.json({ data: letters, meta: {} });
});
const server = app.listen(0, async () => {
const base = `http://localhost:${server.address().port}/letters`;
for (const qs of ['', '?page=4', '?page=2&limit=50', '?page=-3&limit=0']) {
const res = await fetch(base + qs);
console.log(await res.text());
}
server.close();
});{"data":["a","b","c","d","e","f","g","h","i","j"],"meta":{}}
{"data":["a","b","c","d","e","f","g","h","i","j"],"meta":{}}
{"data":["a","b","c","d","e","f","g","h","i","j"],"meta":{}}
{"data":["a","b","c","d","e","f","g","h","i","j"],"meta":{}}
Show solution
app.get('/letters', (req, res) => {
const toInt = (v, fallback) => (Number.isNaN(Number.parseInt(v, 10)) ? fallback : Number.parseInt(v, 10));
const limit = Math.min(5, Math.max(1, toInt(req.query.limit, 3)));
const page = Math.max(1, toInt(req.query.page, 1));
const start = (page - 1) * limit;
res.json({
data: letters.slice(start, start + limit),
meta: { page, limit, total: letters.length, pages: Math.ceil(letters.length / limit) },
});
});limit=0 is a valid integer, so it isn't replaced by the default — the clamp turns it into 1.
7. API key guard
Protect everything under /admin with a middleware: no X-Api-Key header → 401 { "error": "missing api key" }; a key that isn't in KEYS → 403 { "error": "invalid api key" }. /public stays open.
Expected:
/public 200 {"open":true}
/admin/stats 401 {"error":"missing api key"}
/admin/stats 403 {"error":"invalid api key"}
/admin/stats 200 {"orders":12}const express = require('express');
const KEYS = new Set(['k-123']);
const app = express();
function requireApiKey(req, res, next) {
// TODO
next();
}
app.get('/public', (req, res) => res.json({ open: true }));
app.use('/admin', requireApiKey);
app.get('/admin/stats', (req, res) => res.json({ orders: 12 }));
const server = app.listen(0, async () => {
const base = `http://localhost:${server.address().port}`;
const calls = [['/public'], ['/admin/stats'], ['/admin/stats', 'nope'], ['/admin/stats', 'k-123']];
for (const [p, key] of calls) {
const res = await fetch(base + p, { headers: key ? { 'X-Api-Key': key } : {} });
console.log(p, res.status, await res.text());
}
server.close();
});/public 200 {"open":true}
/admin/stats 200 {"orders":12}
/admin/stats 200 {"orders":12}
/admin/stats 200 {"orders":12}
Show solution
function requireApiKey(req, res, next) {
const key = req.get('X-Api-Key');
if (!key) return res.status(401).json({ error: 'missing api key' });
if (!KEYS.has(key)) return res.status(403).json({ error: 'invalid api key' });
next();
}8. Method not allowed
/notes supports GET (list) and POST (create, 201). Any other method should get 405 with the header Allow: GET, POST and body { "error": "method not allowed" } instead of Express's default 404.
Expected:
GET 200 null
POST 201 null
DELETE 405 GET, POST
PUT 405 GET, POSTconst express = require('express');
const app = express();
// TODO: use app.route('/notes') with .get, .post and .all
app.get('/notes', (req, res) => res.json([]));
app.post('/notes', (req, res) => res.status(201).json({ id: 1 }));
const server = app.listen(0, async () => {
const url = `http://localhost:${server.address().port}/notes`;
for (const method of ['GET', 'POST', 'DELETE', 'PUT']) {
const res = await fetch(url, { method });
console.log(method, res.status, res.headers.get('allow'));
}
server.close();
});GET 200 null
POST 201 null
DELETE 404 null
PUT 404 null
Show solution
app.route('/notes')
.get((req, res) => res.json([]))
.post((req, res) => res.status(201).json({ id: 1 }))
.all((req, res) => res.set('Allow', 'GET, POST').status(405).json({ error: 'method not allowed' }));.all() is registered after .get() and .post(), so it only receives the methods those didn't handle.
Test yourself
In exercise 2, why does the 404 response still carry the X-Request-Count header?
- Express adds it automatically
- The middleware ran and set it before Express's final 404 handler
- 404 responses copy headers from the previous request
- It doesn't
In exercise 8, why must .all() come after .get() and .post()?
.all()must always be last in a file- Routes match in order; placed first it would answer every method with 405
- Express sorts methods alphabetically
- It doesn't matter