APIs with Express · Chapter 28 of 29
Build your own Express
By the end of this chapter you can write a small Express yourself, with node:http only, and explain what app.use, next and an error handler really do. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.
- Part: The interview
- 6 tasks
- Express
- In the all labs plan
The first 2 chapters of APIs with Express are free. This one comes with the all labs plan.
Why you need this
The funding round is next week, and Dev, Tapri's new CTO, runs the last interview himself. He shares an empty file: "You have used Express for a month. Now build it, about a hundred lines. I care less about finishing than about how you think about the pipeline."
Using Express is not the same as knowing it. Without a picture of what happens inside, the rules are things to memorise: why order matters, why an error handler with three parameters is silently skipped, why a rejected promise once hung a request. Build it once and each rule follows from the code. It is one of the most common senior Node interview rounds.
What you build: 6 tasks
Each task has tests. You write the code in the lab's editor and press Check.
- Task 1 · interview question
Interview: miniExpress, GET and POST routes with a 404 for the rest
Export miniExpress(), which returns app: a function (req, res) that http.createServer can use, with only node:http, no express import. app.get(path, ...handlers) and app.post(path, ...handlers) register handlers for that method and path, and each returns app, so calls chain.
A path matches exactly, apart from a trailing slash (/menu/ reaches the /menu route); the query string is ignored for matching (GET /menu?veg=true reaches it). The check's handlers answer with res.statusCode and res.end, so GET /menu answers 'the menu', POST /orders answers 201.
A request no route answers gets 404 with the text 'Cannot <METHOD> <path>', the path without the query: POST /menu (wrong method) gets 'Cannot POST /menu', GET /menu/extra gets 'Cannot GET /menu/extra', and GET /men is a 404 too. Each miniExpress() has its own routes.
- Task 2 · interview question
Interview: res.status and res.json, the helpers that chain
Before any handler runs, every res gets two helpers. res.status(code) sets the status code and returns res. res.json(value) sets Content-Type to exactly 'application/json; charset=utf-8', sends the value as JSON, ends the response and returns res.
res.status(201).json({ id: 1, item: 'masala-chai', total: 80 }) answers 201 with that body; res.json alone answers 200; res.json(null) sends the text null.
- Task 3 · interview question
Interview: :params in req.params and the query in req.query
A :name part of a route path matches exactly one segment and lands URL-decoded in req.params: '/menu/:id' with GET /menu/bun%20maska?size=large&sugar=less gives req.params { id: 'bun maska' }, req.query { size: 'large', sugar: 'less' } and req.path '/menu/bun%20maska' (the path without the query, not decoded). GET /menu/chai gives req.query {}. '/orders/:orderId/items/:itemId' with /orders/42/items/3 gives { orderId: '42', itemId: '3' }; every value is a string.
GET /menu/ and GET /menu/a/b do not match '/menu/:id' (404). The other parts of a path match literally: '/v1.0/ping' matches /v1.0/ping but not /v1x0/ping.
- Task 4 · interview question
Interview: app.use and next(), in the order they were added
app.use([prefix], ...fns) registers middleware for every method, returning app. With no prefix it runs for every path; with '/admin' for /admin and everything under it (/admin/stock), on whole segments only: never /administrator. req.url is not changed.
Every function, middleware or route handler, gets (req, res, next), and they run in the order they were added, middleware and routes mixed. next() runs the next one that matches, so a route can take several handlers, and a route that calls next() lets a later middleware or route try. A function that answers without calling next() ends the walk.
With a logger, a '/admin' guard (403 { error: 'Operations only' } without x-role: ops), a /admin/stock route with two handlers, a /menu/:id route that calls next(), a middleware, then /menu/special: GET /menu/special runs the logger, the :id route, the middleware, and answers { special: true }.
- Task 5 · interview question
Interview: errors go to the middleware with four parameters
next(err) skips to the next matching function that has four parameters, (err, req, res, next); without an error those functions are skipped, and with one, every other function is. An error handler that calls next(err) passes the error to the next one.
A handler that throws, or returns a promise that rejects (an async handler), counts as next(err). In the check, next(err), a throw and an async throw all reach the first error handler, which calls next(err), and then the second, which answers 503 { error: <message> }; the normal middleware between them does not run.
When no error handler is left, the app answers err.status if it is a whole number, else 500, with the standard reason phrase from STATUS_CODES as text: 500 'Internal Server Error', and a 418 error gets "I'm a Teapot". Never the error's own message.
- Task 6 · interview question
Interview: json(), a body parser for miniExpress
Export json(), which returns a middleware like express.json(). For a request whose Content-Type starts with application/json (with or without '; charset=utf-8') it reads the whole body and sets req.body to the parsed value ({ item: 'masala-chai', qty: 2 }, or [1, 2]); an empty body gives {}. Other requests (text/plain) go straight on, with req.body left undefined.
Bad JSON ('{"item": ') calls next(err) with err.status 400: with no error handler the client gets 400 'Bad Request', and an app's own error middleware gets the error with status 400 and can answer { error: 'Send valid JSON' }.
What you will learn
- An app is a function: (req, res) with methods attached, ready for http.createServer.
- One stack and a pointer: every use and route in one list, and next walking it.
- Taking a URL apart: the path, the query, decoded values and safe patterns.
- Errors and bodies: error handlers told apart by their parameters, and a body read from a stream.
More in The interview
Build "Build your own Express" yourself
Partner cafés want Tapri’s menu online by Friday: you build its API. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.
The first 2 chapters of APIs with Express are free. This one comes with the all labs plan.