Chain of responsibility and middleware
- Lesson 22 of 32
- 11 min
- Intermediate
- 13 steps
Copying the same login check into every route works until you forget one. You will move each task into its own handler, chain them in a row and see the two mistakes that cost the most: forgetting `next()` and getting the order wrong.
- Copies of the auth check
- 1
- Handlers that ran
- 3
- Response
- 200
- request
- response
- slow request
Step 1 of 13
Problem
A handler that does everything
You have an Express API with the route GET /me, which returns the user's profile. Before answering, the handler writes the request to the log and checks that it carries the `Authorization` header; if it does not, it answers 401.
It works, but that function mixes three jobs: logging, authorising and answering. The first two have nothing to do with the user's profile, and you will need them in almost every route.
What changed
- log and auth check inside GET /me
Step 2 of 13
Problem
The same `if` in every route
GET /orders and POST /orders arrive. Each needs the same check, so you copy it: that makes 3 copies of the same if, as the panel marks.
If tomorrow the token check changes, you have to edit all three. And if someone adds a new route and forgets to paste the if, that route is left open and nothing warns you.
What changed
- GET /orders and POST /orders
- 2 more copies of the check
Step 3 of 13
Concept
A row of handlers
Another way: move each task into its own handler and put them in a row. The request enters through log, which records it and passes it on; it goes to auth, which checks it and passes it on; and it reaches the route, which answers. The response comes back the same way.
That is Chain of Responsibility, one of the 23 patterns in the book by Gamma, Helm, Johnson and Vlissides (1994): whoever sends the request does not know which object in the chain will handle it. In the book's version each link handles it or passes it on; in middleware each one does its part and passes it on.
What changed
- log and auth handlers
- the if copied into every route
Step 4 of 13
Technique
All with the same shape
To be chained, every link fits the same type, Handler: it gets the request and a next function that calls the next one. Each one decides: call `next()` or answer itself and stop.
auth does exactly that in one line: if there is a user, next(); if not, "401 Unauthorized". log is just as short: console.log("->", req.path); return next();. The route is the last link, so it does not even use next.
What changed
- type Handler
- log, auth and route fit Handler
Step 5 of 13
Technique
Who builds the row
The chain function takes the list of handlers and returns a single one. Inside, run(i) calls handler number i and passes it, as next, a function that calls run(i + 1).
So each handler only knows the next one, never the whole chain. Adding a step means adding an item to the list [log, auth, route]: neither log nor route changes.
What changed
- chain([log, auth, route])
Step 6 of 13
Solution
`auth` stops the chain
A request without a user arrives. log records it and calls next(); auth sees that user is missing and answers "401 Unauthorized" without calling `next()`. The route never hears about it: only 2 of the 3 handlers ran.
That is the point: the check lives in one place and protects every route behind it in the row. That is why the count of copies of the check stays at 1, however many routes you add.
What changed
- auth answers 401
- route does not run
Step 7 of 13
Concept
You already use it: Express middleware
In Express each middleware gets req, res and next. According to its documentation, a middleware can run any code, change req and res, end the request-response cycle or pass control to the next one with next().
app.use adds a link to the row. requireAuth is our auth: it answers 401 or calls next(). The GET /me route is the last link and ends the cycle with res.json.
What changed
- auth → requireAuth
- chain([...]) → app.use(...)
Step 8 of 13
Problem
Forgetting `next()` leaves the request hanging
One day someone edits logger and deletes the next(). The middleware records the request and... nothing else: it neither answers nor passes control. The Express docs are clear: if a middleware does not end the cycle, it must call `next()`; otherwise the request is left hanging.
There is no error and no exception: the client just waits. So when a route «never answers», check the middleware that runs before it first.
What changed
- next() in logger
- the client waits with no response
Step 9 of 13
Problem
The order decides what is protected
Now someone registers the route before requireAuth. The request goes through logger, reaches GET /me and the route answers 200 with the profile, with no login. requireAuth never runs, because the route already ended the cycle.
Express runs middleware and routes in the order you register them. A check placed behind the route protects nothing. Build the row in one file and put first whatever can stop the request.
What changed
- app.get before app.use(requireAuth)
- requireAuth does not run
Step 10 of 13
Concept
You already use it: Axios interceptors
The same idea lives on the client side. In Axios, a request interceptor gets the config of every call, can change it (for example, set the Authorization header) and returns it so it goes on its way.
Mind the order: according to the Axios docs, request interceptors run in reverse of the order you add them (last in, first out), and response interceptors in the order you add them. To remove one, keep the id that use() returns and pass it to eject().
What changed
- log → addToken
- auth → logRequest
Step 11 of 13
Concept
Three wrong ideas
«The order does not matter»: you saw that a check behind the route protects nothing, and that in Axios the order of request interceptors is reversed.
«Every handler has to run»: no. Any of them can stop the chain by answering, and that is exactly what auth does with the 401.
«It is an Express thing»: it is a 1994 pattern, older than Express. You will meet it under other names: middleware, interceptors, filters.
Step 12 of 13
Trade-off
When not to build a chain and what it costs
If your flow is two fixed steps that never change, calling two functions one after the other is clearer than a chain. And if only one route needs a step, Express lets you put it on that route alone: app.get("/me", requireAuth, sendProfile).
The cost shows up when debugging: with many links, it is hard to tell who answered or who forgot next(). Give your handlers names and log which one stopped the chain.
Step 13 of 13
Summary
A row of handlers that pass or stop
When several routes share steps (logging, authentication, validation), move each step into a handler with the same shape and put them in a row: each one does its part and calls next(), or answers and stops.
Watch two things: the order (what stops goes before what it protects) and that every link answers or calls `next()`. If the flow is fixed and short, you do not need it.
← → step · R replay · Space pause
You will learn
- Spot the problem: the same check copied into every handler. (covered)
- Build a chain of handlers where each one does its part and calls `next()`. (covered)
- Stop the chain early: answer 401 without reaching the route. (covered)
- Recognise the chain in Express middleware and in Axios interceptors. (covered)
- Avoid the two classic mistakes (forgetting `next()` and the order) and know when not to use it. (covered)