The Analogy: The Hotel Front Desk
A grand hotel puts a single long front desk between the revolving door and everything else. Every guest, courier, and contractor who walks in stops there first, states what they want, and the clerk decides where they go. Nobody wanders into the kitchen or the laundry on their own; the desk is the one opening through which every arriving request must pass.
The clerk works from a routing chart pinned under the counter. It pairs a kind of request with a destination: room keys to the key cabinet, a spa booking to the spa telephone, a lost passport to the duty manager, a parcel to the loading dock. Each line names a request and the action that answers it, and the clerk simply reads down the chart until a line matches what the visitor asked for.
Because the chart is explicit, the desk stays calm as the hotel grows. Add a new service, say a guided tour, and you add one line naming who handles it; the clerk needs no retraining and the lobby is not rearranged. Every visitor is dealt with by exactly the station the chart names for their request, and then sent on their way while the next person steps up.
The failure shows itself the moment a request arrives that nobody charted. A guest asks to exchange a currency the hotel does not handle, and the clerk, having read to the bottom of the chart without a match, is left holding a person with nowhere to send them. If there is no final line reading anything not listed above goes to the duty manager, the guest just stands at the counter unanswered while the queue behind them lengthens.
Syntax or Core Structure
Express is a thin web framework for Node.js. Node can already open a network socket and speak HTTP by itself, but doing so by hand means parsing request lines and writing raw status codes for every single route. Express is the front desk that sits on top of that socket: you describe which requests go where, and it handles the matching and the plumbing underneath.
The smallest useful server creates an app, pins a few routes to the routing chart, adds a catch-all line for anything unmatched, and opens the socket. Each app.get call is one line of the chart: a path and the function that answers it.
const express = require('express');
const app = express();
app.get('/', function (req, res) {
res.send('Front desk: welcome');
});
app.get('/health', function (req, res) {
res.json({ status: 'ok', service: 'front-desk' });
});
app.get('/rooms/:number', function (req, res) {
res.send('Room ' + req.params.number + ' requested');
});
app.use(function (req, res) {
res.status(404).send('No desk handles ' + req.method + ' ' + req.url);
});
app.listen(3000, function () {
console.log('Front desk listening on port 3000');
});
Install Express and start the file with Node.
npm install express
node server.js
The banner prints and the process stays alive, holding the socket open for callers. From another terminal you can knock on each route with curl and read what the desk sends back.
curl -s http://localhost:3000/
curl -s http://localhost:3000/health
Output:
Front desk: welcome
{"status":"ok","service":"front-desk"}
Every handler receives two objects. The first, conventionally named req, describes the incoming request: its path, its method, its query string, and any parameters pulled from the path. The second, res, is how you answer: res.send writes text or HTML, res.json serialises an object and sets the JSON content type, and res.status sets the numeric code before the body goes out.
Technical Depth: Routing, Route Parameters, and Status Codes
Routing is the whole job of the front desk, and Express matches routes in the order you declare them. The first line whose method and path pattern fit the request wins, its handler runs, and the search stops there. This is exactly why the catch-all belongs last: it is the duty-manager line that only fires when nothing above it matched.
Route Parameters
A colon in a path marks a slot that captures whatever the caller puts there. The route /rooms/:number matches /rooms/204 and hands you the captured text as req.params.number. Parameters always arrive as strings, so convert them when you need a real number.
Calling the parameterised route and then an uncharted path shows both the capture and the catch-all at work. The bracket at the end is curl reporting the status code it received.
curl -s -w ' [%{http_code}]' http://localhost:3000/rooms/204
curl -s -w ' [%{http_code}]' http://localhost:3000/missing
Output:
Room 204 requested [200]
No desk handles GET /missing [404]
Status Codes That Matter
The status code is the desk's one-word verdict on a request, read before anyone examines the body. A small handful cover almost everything a simple API needs to say.
| Code | Name | Means |
|---|---|---|
| 200 | OK | The request succeeded and a body follows |
| 201 | Created | A new resource was stored, often after a POST |
| 400 | Bad Request | The caller sent something malformed or missing |
| 404 | Not Found | No route matched and the catch-all replied |
| 500 | Server Error | The handler threw and nothing caught it |
Query Strings
Anything after a question mark in the URL is a query string, and Express parses it into req.query with no extra setup. A request to /search?term=beds&limit=3 exposes req.query.term and req.query.limit, both as strings, so the same convert-and-default care applies. Query values are optional by nature, which makes them the right home for filters and paging rather than for data a route cannot run without.
app.get('/search', function (req, res) {
const term = req.query.term || 'nothing';
const limit = Number(req.query.limit || 10);
res.json({ term: term, limit: limit });
});
Calling it once with both parameters and once with none shows the defaults filling in.
curl -s -w ' [%{http_code}]' 'http://localhost:3000/search?term=beds&limit=3'
curl -s -w ' [%{http_code}]' 'http://localhost:3000/search'
Output:
{"term":"beds","limit":3} [200]
{"term":"nothing","limit":10} [200]
Sending Text or JSON
The res.send method inspects what you hand it: a string goes out as text or HTML. Prefer res.json whenever you mean to return data, because it states the intent plainly and always sets the JSON content type so clients parse it correctly. The health route above used res.json, and its body came back as a compact JSON string with no spaces, which is exactly what an API client expects to receive.
Real World Example: A Guest Register API
The front desk becomes genuinely useful the moment it remembers something. This small guest register keeps an in-memory list, accepts new guests over POST, checks that a name was actually supplied, and lets callers read the whole list or fetch one guest by id. It wires in express.json() so that JSON request bodies are parsed into req.body before any handler runs.
const express = require('express');
const app = express();
app.use(express.json());
const guests = [];
let nextId = 1;
app.get('/guests', function (req, res) {
res.json({ count: guests.length, guests: guests });
});
app.post('/guests', function (req, res) {
const name = req.body.name;
if (!name) {
return res.status(400).json({ error: 'name is required' });
}
const guest = { id: nextId++, name: name };
guests.push(guest);
res.status(201).json(guest);
});
app.get('/guests/:id', function (req, res) {
const id = Number(req.params.id);
const found = guests.find(function (g) { return g.id === id; });
if (!found) {
return res.status(404).json({ error: 'no guest with id ' + id });
}
res.json(found);
});
app.listen(3000, function () {
console.log('register listening on port 3000');
});
Exercise it with a short sequence of curl calls: create two guests, then try an empty body to see the validation refuse it.
curl -s -w ' [%{http_code}]' -H 'Content-Type: application/json' -d '{"name":"Ada"}' http://localhost:3000/guests
curl -s -w ' [%{http_code}]' -H 'Content-Type: application/json' -d '{"name":"Grace"}' http://localhost:3000/guests
curl -s -w ' [%{http_code}]' -H 'Content-Type: application/json' -d '{}' http://localhost:3000/guests
Output:
{"id":1,"name":"Ada"} [201]
{"id":2,"name":"Grace"} [201]
{"error":"name is required"} [400]
Then read the collection back and pull one guest by id, including an id that was never created.
curl -s -w ' [%{http_code}]' http://localhost:3000/guests
curl -s -w ' [%{http_code}]' http://localhost:3000/guests/2
curl -s -w ' [%{http_code}]' http://localhost:3000/guests/99
Output:
{"count":2,"guests":[{"id":1,"name":"Ada"},{"id":2,"name":"Grace"}]} [200]
{"id":2,"name":"Grace"} [200]
{"error":"no guest with id 99"} [404]
Each POST runs express.json() first, which reads the request body and parses it into req.body; only then does the handler see the name. A missing name short-circuits with a 400 before anything is stored, so the list never fills with nameless records, and the return in front of that response is what stops the handler from running on to push a broken entry.
The two read routes show the split Express quietly encourages: a collection route that returns everything with a count, and a parameterised route that turns the id from the path into a single lookup. Because ids arrive as strings, the handler converts with Number before comparing, since otherwise a numeric stored id would never equal the raw string taken from the URL.
The register is deliberately small, and its shortcuts are themselves the lesson. The list lives only in memory, so every guest vanishes when the process restarts and nextId resets to one; run two copies behind a load balancer and both cheerfully hand out id 1. It checks only that a name is present, not that it is sensible, so an empty string that slipped past trimming or a megabyte of text would be accepted. There is no authentication, so anyone who can reach the port can add records; the collection route returns everything with no pagination, fine for a demo and ruinous for a real dataset; and the lookup scans the whole array every time, which is linear rather than indexed.
Common Mistakes
- Placing the catch-all before the real routes. Express matches in declaration order, so a 404 handler registered first answers every request and the real routes below it never get a turn.
- Forgetting express.json(). Without that middleware the body is never parsed, so req.body is undefined on every POST, and reading a field off it throws before the handler can do anything useful.
- Trusting a route parameter to be a number. Values in req.params always arrive as strings; store or compare one without converting and a numeric lookup quietly fails to match anything.
- Never sending a response on some branch. If a handler falls through a condition without calling res.send or res.json, the request simply hangs open until the client gives up and times out.
- Sending a second response after one already went out. Calling res.json after an early res.status().json() without a return in front triggers the headers already sent error, which is confusing until you spot the missing return.
- Hardcoding the port. A fixed literal breaks on hosts that hand you the port through an environment variable; read process.env.PORT with a local fallback so the same code runs everywhere.
- Mismatching the HTTP method. Defining app.get for a form the browser submits as POST means the request falls straight through to the catch-all, even though the path itself looks perfectly right.
- Piling every route into one growing file. It works at first, but with no plan to divide the routes the file soon becomes unreadable, which is precisely the problem the Router exists to solve later in this track.
- Returning a plain string where clients expect JSON. Answering one route with res.send of a bare word while others use res.json hands the client an inconsistent content type, and its JSON parser chokes on the unquoted text.
Best Practices
- Declare routes from most specific to most general, and keep the catch-all last. Because matching stops at the first hit, this ordering guarantees each request reaches the narrowest handler that fits before the duty-manager line ever runs.
- Mount express.json() once, near the top, ahead of the routes that need it. Body parsing set up in a single place keeps every POST handler simple, with no risk of one route forgetting to parse while another remembers.
- Return the moment you send a response. Writing return in front of res.send or res.json in every early-exit branch makes it impossible to accidentally answer the same request twice.
- Match the status code to the outcome. Send 201 when you create a resource, 400 when the caller's input is wrong, and 404 when nothing matched, so clients can branch on the code without first parsing the body.
- Read the port from process.env.PORT with a sensible fallback. The same file then runs unchanged on your laptop and on a host that assigns the port for you, which is the difference between a demo and something you can deploy.
- Keep handlers thin by validating first and delegating the real work. A handler that checks its input and then calls one small named function stays readable and is far easier to test than a handler that does everything inline.
- Return errors as JSON objects with a consistent shape. When every failure comes back as an object carrying the same error field, clients write one error path instead of guessing whether today's failure is a bare string or an object.
- Never trust req.body. Check that the fields you need are present and of the type you expect before using them, because the body is whatever the caller chose to send, not what you were hoping to receive.
Practice Exercises
- Build the front desk from scratch. Create a server with a root route, a health route that returns JSON, and a catch-all that answers unknown paths with a 404, then confirm each response and its status code with curl.
- Add a parameterised lookup. Add a route such as /rooms/:number that reads the parameter, converts it with Number, and returns a message that differs for even and odd room numbers, proving to yourself that the parameter really is a string until you convert it.
- Introduce a deliberate ordering bug and then fix it. Move the catch-all above your real routes, watch every request come back as a 404, then move it back to the bottom and explain in one sentence why declaration order alone decided the outcome.
- Extend the guest register. Add a DELETE /guests/:id route that removes a matching guest and returns 204 on success or 404 when the id is unknown, then confirm both cases with curl and check that a following GET reflects the removal.