Explain it simply
Explain it simply
Writing a server with the http module is like reading, sorting and answering every slip at the counter yourself. Express hangs a sign over the counter: "GET /health goes to this person, POST /orders goes to that one". Each time a slip arrives, Express reads the sign and hands it to the right function.
Answering gets easier too. Write res.json({ status: 'ok' }) and Express turns the object into a JSON string, adds the Content-Type header and finishes the response. Express does not replace the http module; it adds a helpful layer on top of it.
Problem → Why → Solution
The problem: the if chain keeps growing
In the previous lesson's raw http server, every new route means another else if, and every JSON answer repeats writeHead, Content-Type and JSON.stringify. Want to log every request? Then you wonder whether to paste a console.log into every branch. By about ten routes, the one handler is a long function that is hard to read and risky to change.
http.createServer((req, res) => {
console.log(req.method, req.url); // logging, mixed into routing
if (req.method === 'GET' && req.url === '/health') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ status: 'ok' }));
} else if (req.method === 'GET' && req.url === '/users') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(users));
} else if (/* ...eight more routes... */ false) {
} else {
res.writeHead(404); res.end();
}
});Why reach for a framework?
Three jobs are tangled in one function: routing (which code handles which request), cross-cutting work (logging, parsing bodies, checking auth) and sending responses. Express gives each route its own function and pulls the per-request work out into middleware, so each piece of code has a single job.
Core concept: the app, routes and the middleware chain
const app = express() creates an application object. app.get(path, handler), app.post(), app.put() and app.delete() register routes: "when this method and path arrive, call this handler". app.listen(port, callback) calls http.createServer(app) internally and returns the resulting http.Server, so server.address() and server.close() from the previous lesson still work.
Express extends req and res with helpers. res.send(value) chooses the Content-Type from the value: a string becomes text/html, an object or array becomes JSON. res.json(value) always sends JSON, and res.status(404) sets the status and returns res, so you can chain res.status(404).json({...}). req.path is the path without the query string, and req.query turns the query string into an object.
Middleware is a function with three parameters: (req, res, next). You register it with app.use(fn) and every request passes through it. A middleware either sends the response itself or calls next() to hand over to the next middleware or route; if it does neither, the request hangs. Express tries middleware and routes in the order you registered them, which is why a logger goes at the top and the 404 handler at the very bottom.
This tutorial uses Express 5. It requires Node 18 or newer, and when an async handler throws (its Promise rejects), Express 5 forwards the error to your error-handling middleware automatically. In Express 4 you had to write try/catch and call next(err) yourself; the next lesson looks at this in detail.
Add Express to a project with npm install express; unlike http, it does not ship with Node.js. A route runs only when both the method and the path match, so app.get('/health') does not answer POST /health: that request keeps going down the chain and lands in the 404 handler.
- A request arrives
- Middleware runs in order via next()
- The first matching route answers
- Nothing matched: the 404 handler
Once a response is sent the chain stops; routes further down are never tried.
General pattern
import express from 'express';
const app = express();
app.use((req, res, next) => { /* every request */ next(); });
app.METHOD('/path', (req, res) => {
res.status(CODE).json(data); // or res.send(text)
});
app.use((req, res) => res.status(404).json({ error: 'Not found' }));
const server = app.listen(PORT, () => { /* ready */ });Order matters: per-request middleware first, then routes, then the 404 fallback last. Replace METHOD with get, post, put, patch or delete.
Example: a logger, two routes and a 404
This app has a middleware that logs every request, a home route that returns text, a /health route that returns JSON, and a JSON 404 handler. It listens on port 0 and sends three requests with fetch. The [server] lines come from the middleware and the [client] lines from fetch, so you can follow each request's trip in order.
import express from 'express';
const app = express();
// Middleware: runs for every request, then hands over with next()
app.use((req, res, next) => {
console.log(`[server] ${req.method} ${req.url}`);
next();
});
app.get('/', (req, res) => {
res.send('Hello from Express!');
});
app.get('/health', (req, res) => {
res.json({ status: 'ok', service: 'nodejs-tutorial' });
});
// Registered last: only reached when no route above answered
app.use((req, res) => {
res.status(404).json({ error: `No route for ${req.method} ${req.path}` });
});
const server = app.listen(0, async () => {
const base = `http://localhost:${server.address().port}`;
for (const path of ['/', '/health', '/admin']) {
const res = await fetch(base + path);
const type = res.headers.get('content-type');
console.log(`[client] ${res.status} ${type} ${await res.text()}`);
}
server.close();
});Code breakdown
- Middleware
app.use((req, res, next) => {With no path given, it runs for every request. It logs, then calls next() so the request continues to the routes below.
- Text response
res.send('Hello from Express!');A string makes Express choose text/html; charset=utf-8, as the output shows. Without an explicit status, it is 200.
- JSON response
res.json({ status: 'ok', service: 'nodejs-tutorial' });Express does the JSON.stringify and sets application/json; what took two lines with raw http is one here.
- 404 fallback
res.status(404).json({ error: `No route for ${req.method} ${req.path}` });Sitting at the bottom, it is reached only when no route above answered. Without it, Express's default reply is an HTML page reading "Cannot GET /admin".
- listen returns the server
const server = app.listen(0, async () => {app.listen() returns the http.Server, kept in a variable to read the port and to close() it at the end.
[server] GET /
[client] 200 text/html; charset=utf-8 Hello from Express!
[server] GET /health
[client] 200 application/json; charset=utf-8 {"status":"ok","service":"nodejs-tutorial"}
[server] GET /admin
[client] 404 application/json; charset=utf-8 {"error":"No route for GET /admin"}Raw http and Express side by side
Express does not hide the http module: req is still an http.IncomingMessage and res is still an http.ServerResponse. That is why things from the previous lesson, such as res.setHeader() and req.headers, keep working inside an Express handler. The table compares what Express layers on top. Choosing a framework is not about avoiding raw http; it is about not writing the same plumbing again and again.
| Task | Raw http | Express |
|---|---|---|
| Routing | if (req.method === ... && req.url === ...) | app.get('/path', handler) |
| Sending JSON | writeHead + JSON.stringify + end | res.json(data) |
| Reading the query | new URL(req.url, base).searchParams | req.query |
| Per-request work | Repeated in every branch | app.use(middleware) |
In real projects
Where this shows up in real projects
Express is one of the most widely used Node.js web frameworks, found behind REST APIs, mobile app backends and server-rendered websites. Open the app.js of a production app and the top is usually a long list of middleware: helmet for security headers, cors to allow cross-origin requests, express.json() to read JSON bodies, a request logger and so on. Routes follow, with the 404 and error handlers at the bottom.
An endpoint like /health is genuinely useful: load balancers, Kubernetes and uptime monitors call it every few seconds and stop routing traffic to, or restart, an instance that stops answering 200. Tests start the app on port 0 and check it with fetch, exactly as in this lesson.
Common mistakes
Common mistakes
1. Forgetting next() in middleware
A logger that calls console.log but not next() stops every request right there, and the browser keeps loading. No error is printed, which makes it hard to track down. Every middleware must either send a response or call next().
2. Registering the 404 handler above the routes
Write app.use((req, res) => res.status(404)...) before your app.get() calls and, because a path-less app.use() matches everything, every URL including /health returns 404. Keep fallbacks at the bottom of the file.
3. Sending two responses
if (!user) res.status(404).json(...) without a return keeps running into res.json(user), which throws ERR_HTTP_HEADERS_SENT. Write return res.status(404).json(...) to leave the handler immediately, so each request produces exactly one response.
Best practices
Best practices
- Keep the code that builds the app separate from app.listen(), so tests can start the app on port 0 themselves.
- Let API routes return JSON only, and shape 404s and errors the same way, as { error: '...' }.
- Read the port from process.env.PORT instead of hard-coding it.
Mini challenge
Mini challenge: a request-counter middleware
Write an Express app with a middleware that counts requests, a /stats route that reports the count, and a JSON 404 handler, then test it with fetch.
- The middleware increments a counter on every request and calls next()
- GET / returns the text 'Welcome'
- GET /stats returns JSON { requests: <count> }
- Call /, /nope and /stats in order, print status and body, then close the server
import express from 'express';
const app = express();
let requests = 0;
// TODO: middleware that counts every request
// TODO: GET / -> 'Welcome'
// TODO: GET /stats -> { requests }
// TODO: 404 handler -> { error: 'Not found' } (registered last)
const server = app.listen(0, async () => {
// TODO: fetch '/', '/nope', '/stats'; print "<status> <body>"; close the server
});Expected: Expected output: 200 Welcome 404 {"error":"Not found"} 200 {"requests":3}
Show hint
The counting middleware must sit above the routes so the 404 request to /nope is counted too. The /stats request itself is also counted before its handler runs.
Show solution
import express from 'express';
const app = express();
let requests = 0;
app.use((req, res, next) => {
requests += 1;
next();
});
app.get('/', (req, res) => res.send('Welcome'));
app.get('/stats', (req, res) => res.json({ requests }));
app.use((req, res) => res.status(404).json({ error: 'Not found' }));
const server = app.listen(0, async () => {
const base = `http://localhost:${server.address().port}`;
for (const path of ['/', '/nope', '/stats']) {
const res = await fetch(base + path);
console.log(res.status, await res.text());
}
server.close();
});Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Express adds routing, middleware and response helpers on top of the http module.
- app.METHOD(path, handler) registers routes and app.use() registers middleware; Express tries them in order.
- Every middleware must either send a response or call next().
- res.json() and res.status().json() handle headers and stringify; keep the 404 handler at the bottom.
Using middleware — Express.js