You want every request that reaches notes-api logged in the terminal. If console.log(req.method + " " + req.url) goes into every handler, five routes means five identical lines. Once a sixth route appears, that line is easy to forget.
Express has a place for work that applies to many routes at once: middleware. Middleware is a function that runs between the moment a request arrives and the route's handler. It can read or add something to req, stop the request by answering right away, or pass the request on to the next one with next(). Think of the checkpoints at an airport, with the request as a traveller going through them. Each checkpoint is one middleware, and each one can say "go ahead" (next()) or "stop" (answer right away). If one officer forgets to let the traveller through, the traveller just keeps standing there.
Middleware: a function with req, res, next
const express = require("express");
const app = express();
app.use(express.json());
function logger(req, res, next) {
console.log(req.method + " " + req.url);
next();
}
app.use(logger);
app.get("/notes", (req, res) => {
res.json(notes);
});
- Middleware has a third parameter,
next: a function that passes the request on to the next middleware or handler. app.use(logger)installsloggerfor every request, whatever its method and path.app.use(express.json())is middleware too: Express's own middleware, which reads a JSON body and puts it inreq.body.
The notes array and app.listen are the same as in the previous lesson. Start the server with node app.js, then send two requests, GET /notes and POST /notes. The server's terminal prints:
Server running at http://localhost:3000
GET /notes
POST /notes
next(): pass it on
Every middleware has to do one of two things: call next(), or send an answer (res.json, res.send, ...). Say you remove the next() line from logger. The server terminal still writes GET /notes, but the request stops there. The handler never runs, no answer is ever sent, and curl keeps waiting. With a 5 second limit (curl -i -m 5 http://localhost:3000/notes):
curl: (28) Operation timed out after 5002 milliseconds with 0 bytes received
There's no error on the server. The request just hangs: the client keeps waiting with no answer.
Order = the order of app.use
Express runs middleware and routes in the order you write them:
app.use((req, res, next) => { console.log("A"); next(); });
app.use((req, res, next) => { console.log("B"); next(); });
app.get("/", (req, res) => { res.send("C"); });
GET / prints A then B in the terminal, and then the handler sends C to the browser. Middleware written after a route doesn't run for requests that route already answered, because the route doesn't call next().
A guard middleware for one route
Only a client that brings the API key (a secret code sent in a header) may create a new note. The guard is middleware too:
function checkApiKey(req, res, next) {
if (req.headers["x-api-key"] !== "secret123") {
return res.status(401).json({ error: "Invalid API key" });
}
next();
}
app.post("/notes", checkApiKey, (req, res) => {
const { title, content } = req.body;
const newNote = { id: notes.length + 1, title, content };
notes.push(newNote);
res.status(201).json(newNote);
});
x-api-key header |
What happens | Answer |
|---|---|---|
| none | the guard answers, next() isn't called |
401 {"error":"Invalid API key"} |
wrong |
the same | 401 {"error":"Invalid API key"} |
secret123 |
next(), the handler runs |
201 {"id":3,"title":"Workout","content":"run 5 km"} |
- The middleware sits between the path and the handler:
app.post(path, checkApiKey, handler). Only this route is guarded, andGET /notesstays open. 401 Unauthorizedmeans "you haven't proven who you are yet".- Node stores header names in lower case. Even when
X-API-Keyis sent, you read it asreq.headers["x-api-key"].req.get("x-api-key")works too, and it ignores letter case.
Ready-made middleware
| Middleware | What it's for |
|---|---|
express.json() |
reads a JSON body into req.body |
express.urlencoded({ extended: true }) |
reads the body of an HTML form |
helmet |
sets security headers such as Content-Security-Policy and X-Frame-Options |
cors |
decides which domains may call the API from a browser |
morgan |
logs every request to the terminal, like our logger |
express-rate-limit |
limits the number of requests per IP address (the address of the sending computer), for example 100 a minute |
Middleware from npm needs npm install first (for example npm install helmet), then app.use(helmet()).
📌 Express 5: errors in async middleware
When an async middleware or handler throws, Express 5 passes the error by itself to the part of Express that handles errors, and answers 500. Express 4 doesn't: the error becomes an unhandled rejection (a failed Promise that nothing catches), and Node stops the server. How to handle errors yourself is in the Error Handling lesson.
In the exercise: the guard as a plain function
The exercise doesn't run Express. checkApiKey(headers) takes an object of headers and only returns true or false: return headers["x-api-key"] === "secret123";. The sentences in the output are printed by the code below that function, which is already in the starter:
Request with a valid key: Access granted - This is secret data
Request without a key: Access denied - Invalid API key
⚠️ Middleware that stalls, leaks, or gets skipped
- Forgetting
next(). The request hangs with no error, until the client stops waiting. - Forgetting
returnin the guard. Withoutreturn, the code goes on tonext()afterres.status(401).json(...). The client gets a 401, but the handler still runs and the note is still saved. The server terminal then writesError [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client. app.use(logger)written after the routes. A request a route already answered never reacheslogger.- Upper case header names.
req.headers["X-API-Key"]is alwaysundefined. Write it in lower case.
TL;DR: Middleware is a function (req, res, next) that runs before the handler. Every middleware must either call next() (pass the request on to the next one) or send an answer. With neither, the request hangs: the client waits with no answer (curl: (28) Operation timed out). app.use(fn) installs middleware for every route, in the order written: what is written first runs first. app.post("/notes", checkApiKey, handler) puts the guard checkApiKey on one route only. The guard refuses requests without the API key (a secret code in a header) with return res.status(401).json(...). The return keeps the handler from running. Headers are read in lower case: req.headers["x-api-key"]. express.json() reads the body. From npm come helmet (sets security headers), cors, morgan and express-rate-limit. Express 5 catches errors from async middleware and answers 500, Express 4 doesn't.
⚡ Middleware: req, res, next
Write:
function logger(req, res, next) {
console.log(req.method + " " + req.url);
next();
}
app.use(logger);
Meaning: Middleware is a function (req, res, next) that runs between the moment a request arrives and the route's handler. app.use(logger) installs it for every request, and next() passes the request on to the next middleware or handler.
⚡ Forget next(), the request goes quiet
Guess first: app.use((req, res) => { console.log('Log'); }); and the request never reaches the route. Why?
The middleware neither calls next() nor sends an answer. The request hangs with no error, until the client (the program that sent the request) stops waiting.
Meaning: Every middleware must pick one: call next(), or send an answer. Middleware runs in the order of the app.use lines you wrote.
⚡ A guard for one route
Write:
function checkApiKey(req, res, next) {
if (req.headers["x-api-key"] !== "secret123") {
return res.status(401).json({ error: "Invalid API key" });
}
next();
}
app.post("/notes", checkApiKey, (req, res) => { /* ... */ });
Meaning: checkApiKey refuses a request that doesn't bring the right API key (a secret code in a header), with status 401 (Unauthorized). Middleware placed between the path and the handler guards only that route. Use return when refusing, so the handler doesn't run too. Header names are read in lower case.