Middleware: The Airport Checkpoints
When every endpoint starts by copying the same checks (log the request, make sure someone's signed in), one endpoint forgets one, and every new check is an edit to all of them; middleware gives each check its own small step in a line every request passes through, so each step handles the request or passes it on, which is Pass 3's Chain of Responsibility at work in every web framework.
Journeyman · OOP · Software Development · Updated
After this lesson you can
- Move the checks every request needs into middleware: small steps that each answer the request or pass it on, in the right order
- Spot the smells that point to middleware: the same checks copied at the top of every endpoint, and one endpoint that forgot
- Tell Chain of Responsibility, Decorator and middleware apart by what each one is for
Key takeaways
- The smell: the same checks copied at the top of every endpoint, and one endpoint that forgot one.
- The cause: jobs every request needs (logging, signing in, timing) live inside each endpoint, so nobody owns them.
- The fix: each job is a small step, a middleware, that gets the request and either answers it or passes it on to the next. The endpoints keep only their own work.
- Middleware is Chain of Responsibility (any step may stop the request) with a bit of Decorator (each step wraps the rest, and can act on the way back).
- Order matters: a step only sees what the steps before it let through.
Before this: Chain of Responsibility: The Coin Sorter and Decorator: Same Phone, More Features, both from Pass 3, and MVC.
In Pass 3, a voice command to the HomeBase hub passed a row of checks (is it after 22:00? is someone home? may this person do it, since a guest can't unlock doors?), and any check could stop it. That was Chain of Responsibility, with three checks for one kind of command. The library's web API has the same need on a bigger scale: every request, to every endpoint, should be logged, and every request that changes something needs someone signed in. By the end of this lesson those checks will live in a line of small steps called middleware, and you'll see the same line inside every framework in this pass.
The symptom: one endpoint forgot
An endpoint is the code for one address the API answers, such as GET /books. The library has three so far, and each starts with the checks it needs. Here four requests arrive: one lists the books, two come from someone who isn't signed in, and one from Maya:
Dictionary<string, Func<Request, Response>> endpoints = new()
{
["GET /books"] = ListBooks,
["POST /loans"] = Borrow,
["POST /loans/1/return"] = ReturnBook,
};
foreach (Request request in new[] { new Request("GET", "/books", ""), new Request("POST", "/loans", ""),
new Request("POST", "/loans/1/return", ""), new Request("POST", "/loans", "Maya") })
{
Response response = endpoints[ quot;{request.Method} {request.Path}"](request);
Console.WriteLine( quot;{response.Status} {response.Body}");
}
Response ListBooks(Request request)
{
Console.WriteLine( quot;log: {request.Method} {request.Path}");
return new Response(200, "The Lighthouse Keeper, A Map of Small Things, Rivers of Glass");
}
Response Borrow(Request request)
{
Console.WriteLine( quot;log: {request.Method} {request.Path}");
if (request.User == "") { return new Response(401, "Please sign in"); }
return new Response(201, quot;Loan 1: {request.User}, The Lighthouse Keeper");
}
Response ReturnBook(Request request)
{
Console.WriteLine( quot;log: {request.Method} {request.Path}");
return new Response(200, "Loan 1 returned: late fee $0.00");
}
record Request(string Method, string Path, string User);
record Response(int Status, string Body);
log: GET /books
200 The Lighthouse Keeper, A Map of Small Things, Rivers of Glass
log: POST /loans
401 Please sign in
log: POST /loans/1/return
200 Loan 1 returned: late fee $0.00
log: POST /loans
201 Loan 1: Maya, The Lighthouse Keeper
record Request(String method, String path, String user) { }
record Response(int status, String body) { }
Response listBooks(Request request) {
IO.println("log: " + request.method() + " " + request.path());
return new Response(200, "The Lighthouse Keeper, A Map of Small Things, Rivers of Glass");
}
Response borrow(Request request) {
IO.println("log: " + request.method() + " " + request.path());
if (request.user().isEmpty()) { return new Response(401, "Please sign in"); }
return new Response(201, "Loan 1: " + request.user() + ", The Lighthouse Keeper");
}
Response returnBook(Request request) {
IO.println("log: " + request.method() + " " + request.path());
return new Response(200, "Loan 1 returned: late fee $0.00");
}
void main() {
Map<String, Function<Request, Response>> endpoints = Map.of(
"GET /books", this::listBooks,
"POST /loans", this::borrow,
"POST /loans/1/return", this::returnBook);
for (Request request : List.of(new Request("GET", "/books", ""), new Request("POST", "/loans", ""),
new Request("POST", "/loans/1/return", ""), new Request("POST", "/loans", "Maya"))) {
Response response = endpoints.get(request.method() + " " + request.path()).apply(request);
IO.println(response.status() + " " + response.body());
}
}
log: GET /books
200 The Lighthouse Keeper, A Map of Small Things, Rivers of Glass
log: POST /loans
401 Please sign in
log: POST /loans/1/return
200 Loan 1 returned: late fee $0.00
log: POST /loans
201 Loan 1: Maya, The Lighthouse Keeper
from dataclasses import dataclass
@dataclass
class Request:
method: str
path: str
user: str
@dataclass
class Response:
status: int
body: str
def list_books(request):
print(f"log: {request.method} {request.path}")
return Response(200, "The Lighthouse Keeper, A Map of Small Things, Rivers of Glass")
def borrow(request):
print(f"log: {request.method} {request.path}")
if request.user == "":
return Response(401, "Please sign in")
return Response(201, f"Loan 1: {request.user}, The Lighthouse Keeper")
def return_book(request):
print(f"log: {request.method} {request.path}")
return Response(200, "Loan 1 returned: late fee $0.00")
endpoints = {"GET /books": list_books, "POST /loans": borrow, "POST /loans/1/return": return_book}
for request in [Request("GET", "/books", ""), Request("POST", "/loans", ""),
Request("POST", "/loans/1/return", ""), Request("POST", "/loans", "Maya")]:
response = endpoints[f"{request.method} {request.path}"](request)
print(f"{response.status} {response.body}")
log: GET /books
200 The Lighthouse Keeper, A Map of Small Things, Rivers of Glass
log: POST /loans
401 Please sign in
log: POST /loans/1/return
200 Loan 1 returned: late fee $0.00
log: POST /loans
201 Loan 1: Maya, The Lighthouse Keeper
function listBooks(request) {
console.log(`log: ${request.method} ${request.path}`);
return { status: 200, body: "The Lighthouse Keeper, A Map of Small Things, Rivers of Glass" };
}
function borrow(request) {
console.log(`log: ${request.method} ${request.path}`);
if (request.user === "") { return { status: 401, body: "Please sign in" }; }
return { status: 201, body: `Loan 1: ${request.user}, The Lighthouse Keeper` };
}
function returnBook(request) {
console.log(`log: ${request.method} ${request.path}`);
return { status: 200, body: "Loan 1 returned: late fee $0.00" };
}
const endpoints = new Map([["GET /books", listBooks], ["POST /loans", borrow], ["POST /loans/1/return", returnBook]]);
for (const request of [{ method: "GET", path: "/books", user: "" }, { method: "POST", path: "/loans", user: "" },
{ method: "POST", path: "/loans/1/return", user: "" }, { method: "POST", path: "/loans", user: "Maya" }]) {
const response = endpoints.get(`${request.method} ${request.path}`)(request);
console.log(`${response.status} ${response.body}`);
}
log: GET /books
200 The Lighthouse Keeper, A Map of Small Things, Rivers of Glass
log: POST /loans
401 Please sign in
log: POST /loans/1/return
200 Loan 1 returned: late fee $0.00
log: POST /loans
201 Loan 1: Maya, The Lighthouse Keeper
interface LibraryRequest { method: string; path: string; user: string; }
interface LibraryResponse { status: number; body: string; }
function listBooks(request: LibraryRequest): LibraryResponse {
console.log(`log: ${request.method} ${request.path}`);
return { status: 200, body: "The Lighthouse Keeper, A Map of Small Things, Rivers of Glass" };
}
function borrow(request: LibraryRequest): LibraryResponse {
console.log(`log: ${request.method} ${request.path}`);
if (request.user === "") { return { status: 401, body: "Please sign in" }; }
return { status: 201, body: `Loan 1: ${request.user}, The Lighthouse Keeper` };
}
function returnBook(request: LibraryRequest): LibraryResponse {
console.log(`log: ${request.method} ${request.path}`);
return { status: 200, body: "Loan 1 returned: late fee $0.00" };
}
const endpoints = new Map<string, (request: LibraryRequest) => LibraryResponse>([
["GET /books", listBooks], ["POST /loans", borrow], ["POST /loans/1/return", returnBook]]);
const requests: LibraryRequest[] = [{ method: "GET", path: "/books", user: "" }, { method: "POST", path: "/loans", user: "" },
{ method: "POST", path: "/loans/1/return", user: "" }, { method: "POST", path: "/loans", user: "Maya" }];
for (const request of requests) {
const response = endpoints.get(`${request.method} ${request.path}`)!(request);
console.log(`${response.status} ${response.body}`);
}
log: GET /books
200 The Lighthouse Keeper, A Map of Small Things, Rivers of Glass
log: POST /loans
401 Please sign in
log: POST /loans/1/return
200 Loan 1 returned: late fee $0.00
log: POST /loans
201 Loan 1: Maya, The Lighthouse Keeper
Look at the third request: nobody is signed in, and the book was returned anyway, because the return endpoint copied the log line and forgot the sign-in check. And the board has a new request already: the library closes for an inventory weekend next month, and every request except GET /books must answer "Closed for inventory". That's an edit to every endpoint, and another chance to forget one.
- The symptom: the same checks copied at the top of every endpoint, and one endpoint that forgot one.
- The cause: jobs that every request needs (logging, signing in, and soon the inventory weekend) live inside each endpoint, so nobody owns them.
What would you try?
A helper, CheckSignIn(request), that each endpoint calls first. The check is written once, but each endpoint still has to remember to call it, and the return endpoint is exactly the one that didn't.
One big Handle(request) function with every check, then the endpoints. Now the checks can't be forgotten, but they're tangled together in one function, and the inventory weekend, the next check, means editing it.
What a good fix needs: each check in its own small piece, run for every request before it reaches an endpoint, with a way to add a check (or take one out) without touching the others.
The fix: a line of checkpoints
An airport works this way. Every passenger passes the same checkpoints in the same order: the ticket check, the security scan, the gate. Each checkpoint can stop a passenger, or wave them on to the next. None of the checkpoints knows about the others, and when the airport adds a checkpoint, the others don't change.

In code, each check is a middleware: a small step that's handed the request and the rest of the line (next), and either answers the request itself or passes it on. The steps sit in a line in front of the endpoints, so every request passes them all, in order, and an endpoint keeps only its own work:

A request goes in through every step and comes back out through them in reverse, so a step can do something on the way in, on the way back, or both:

How it got its name
The steps sit in the middle, between the web server that receives the request and the endpoint that does the work: middleware. A request's path through them is the request pipeline. It's the Chain of Responsibility from Pass 3, at work: a line of handlers, each of which may stop the request or pass it along. Web frameworks found it in the early 2000s, when every site needed the same sign-in, logging and error checks, and now every framework in this pass has it.
The classic version: a chain of handlers
First, as Pass 3 built a chain: each step is an object that holds the next one. Logging and sign-in each get a class, the endpoints are the last link, and they no longer check anything:
Step pipeline = new LogStep { Next = new SignInStep { Next = new EndpointStep() } };
foreach (Request request in new[] { new Request("GET", "/books", ""), new Request("POST", "/loans", ""),
new Request("POST", "/loans/1/return", ""), new Request("POST", "/loans", "Maya") })
{
Response response = pipeline.Handle(request);
Console.WriteLine( quot;{response.Status} {response.Body}");
}
record Request(string Method, string Path, string User);
record Response(int Status, string Body);
// One step in the line: it answers the request, or hands it to the next step.
abstract class Step
{
public Step? Next { get; init; }
public abstract Response Handle(Request request);
}
class LogStep : Step
{
public override Response Handle(Request request)
{
Console.WriteLine( quot;log: {request.Method} {request.Path}");
return Next!.Handle(request);
}
}
class SignInStep : Step
{
public override Response Handle(Request request) =>
request.Method != "GET" && request.User == "" ? new Response(401, "Please sign in") : Next!.Handle(request);
}
// The last link: the endpoints, with only their own work in them.
class EndpointStep : Step
{
public override Response Handle(Request request) => quot;{request.Method} {request.Path}" switch
{
"GET /books" => new Response(200, "The Lighthouse Keeper, A Map of Small Things, Rivers of Glass"),
"POST /loans" => new Response(201, quot;Loan 1: {request.User}, The Lighthouse Keeper"),
"POST /loans/1/return" => new Response(200, "Loan 1 returned: late fee $0.00"),
_ => new Response(404, "No such page"),
};
}
log: GET /books
200 The Lighthouse Keeper, A Map of Small Things, Rivers of Glass
log: POST /loans
401 Please sign in
log: POST /loans/1/return
401 Please sign in
log: POST /loans
201 Loan 1: Maya, The Lighthouse Keeper
record Request(String method, String path, String user) { }
record Response(int status, String body) { }
// One step in the line: it answers the request, or hands it to the next step.
abstract static class Step {
Step next;
Step then(Step next) { this.next = next; return this; }
abstract Response handle(Request request);
}
static class LogStep extends Step {
Response handle(Request request) {
IO.println("log: " + request.method() + " " + request.path());
return next.handle(request);
}
}
static class SignInStep extends Step {
Response handle(Request request) {
if (!request.method().equals("GET") && request.user().isEmpty()) { return new Response(401, "Please sign in"); }
return next.handle(request);
}
}
// The last link: the endpoints, with only their own work in them.
static class EndpointStep extends Step {
Response handle(Request request) {
return switch (request.method() + " " + request.path()) {
case "GET /books" -> new Response(200, "The Lighthouse Keeper, A Map of Small Things, Rivers of Glass");
case "POST /loans" -> new Response(201, "Loan 1: " + request.user() + ", The Lighthouse Keeper");
case "POST /loans/1/return" -> new Response(200, "Loan 1 returned: late fee $0.00");
default -> new Response(404, "No such page");
};
}
}
void main() {
Step pipeline = new LogStep().then(new SignInStep().then(new EndpointStep()));
for (Request request : List.of(new Request("GET", "/books", ""), new Request("POST", "/loans", ""),
new Request("POST", "/loans/1/return", ""), new Request("POST", "/loans", "Maya"))) {
Response response = pipeline.handle(request);
IO.println(response.status() + " " + response.body());
}
}
log: GET /books
200 The Lighthouse Keeper, A Map of Small Things, Rivers of Glass
log: POST /loans
401 Please sign in
log: POST /loans/1/return
401 Please sign in
log: POST /loans
201 Loan 1: Maya, The Lighthouse Keeper
from dataclasses import dataclass
@dataclass
class Request:
method: str
path: str
user: str
@dataclass
class Response:
status: int
body: str
class Step:
"""One step in the line: it answers the request, or hands it to the next step."""
def __init__(self, next=None):
self.next = next
class LogStep(Step):
def handle(self, request):
print(f"log: {request.method} {request.path}")
return self.next.handle(request)
class SignInStep(Step):
def handle(self, request):
if request.method != "GET" and request.user == "":
return Response(401, "Please sign in")
return self.next.handle(request)
class EndpointStep(Step):
"""The last link: the endpoints, with only their own work in them."""
def handle(self, request):
match f"{request.method} {request.path}":
case "GET /books":
return Response(200, "The Lighthouse Keeper, A Map of Small Things, Rivers of Glass")
case "POST /loans":
return Response(201, f"Loan 1: {request.user}, The Lighthouse Keeper")
case "POST /loans/1/return":
return Response(200, "Loan 1 returned: late fee $0.00")
case _:
return Response(404, "No such page")
pipeline = LogStep(SignInStep(EndpointStep()))
for request in [Request("GET", "/books", ""), Request("POST", "/loans", ""),
Request("POST", "/loans/1/return", ""), Request("POST", "/loans", "Maya")]:
response = pipeline.handle(request)
print(f"{response.status} {response.body}")
log: GET /books
200 The Lighthouse Keeper, A Map of Small Things, Rivers of Glass
log: POST /loans
401 Please sign in
log: POST /loans/1/return
401 Please sign in
log: POST /loans
201 Loan 1: Maya, The Lighthouse Keeper
// One step in the line: it answers the request, or hands it to the next step.
class Step {
constructor(next = null) { this.next = next; }
}
class LogStep extends Step {
handle(request) {
console.log(`log: ${request.method} ${request.path}`);
return this.next.handle(request);
}
}
class SignInStep extends Step {
handle(request) {
if (request.method !== "GET" && request.user === "") { return { status: 401, body: "Please sign in" }; }
return this.next.handle(request);
}
}
// The last link: the endpoints, with only their own work in them.
class EndpointStep extends Step {
handle(request) {
switch (`${request.method} ${request.path}`) {
case "GET /books": return { status: 200, body: "The Lighthouse Keeper, A Map of Small Things, Rivers of Glass" };
case "POST /loans": return { status: 201, body: `Loan 1: ${request.user}, The Lighthouse Keeper` };
case "POST /loans/1/return": return { status: 200, body: "Loan 1 returned: late fee $0.00" };
default: return { status: 404, body: "No such page" };
}
}
}
const pipeline = new LogStep(new SignInStep(new EndpointStep()));
for (const request of [{ method: "GET", path: "/books", user: "" }, { method: "POST", path: "/loans", user: "" },
{ method: "POST", path: "/loans/1/return", user: "" }, { method: "POST", path: "/loans", user: "Maya" }]) {
const response = pipeline.handle(request);
console.log(`${response.status} ${response.body}`);
}
log: GET /books
200 The Lighthouse Keeper, A Map of Small Things, Rivers of Glass
log: POST /loans
401 Please sign in
log: POST /loans/1/return
401 Please sign in
log: POST /loans
201 Loan 1: Maya, The Lighthouse Keeper
interface LibraryRequest { method: string; path: string; user: string; }
interface LibraryResponse { status: number; body: string; }
// One step in the line: it answers the request, or hands it to the next step.
abstract class Step {
next: Step | null;
constructor(next: Step | null = null) { this.next = next; }
abstract handle(request: LibraryRequest): LibraryResponse;
}
class LogStep extends Step {
handle(request: LibraryRequest): LibraryResponse {
console.log(`log: ${request.method} ${request.path}`);
return this.next!.handle(request);
}
}
class SignInStep extends Step {
handle(request: LibraryRequest): LibraryResponse {
if (request.method !== "GET" && request.user === "") { return { status: 401, body: "Please sign in" }; }
return this.next!.handle(request);
}
}
// The last link: the endpoints, with only their own work in them.
class EndpointStep extends Step {
handle(request: LibraryRequest): LibraryResponse {
switch (`${request.method} ${request.path}`) {
case "GET /books": return { status: 200, body: "The Lighthouse Keeper, A Map of Small Things, Rivers of Glass" };
case "POST /loans": return { status: 201, body: `Loan 1: ${request.user}, The Lighthouse Keeper` };
case "POST /loans/1/return": return { status: 200, body: "Loan 1 returned: late fee $0.00" };
default: return { status: 404, body: "No such page" };
}
}
}
const pipeline = new LogStep(new SignInStep(new EndpointStep()));
const requests: LibraryRequest[] = [{ method: "GET", path: "/books", user: "" }, { method: "POST", path: "/loans", user: "" },
{ method: "POST", path: "/loans/1/return", user: "" }, { method: "POST", path: "/loans", user: "Maya" }];
for (const request of requests) {
const response = pipeline.handle(request);
console.log(`${response.status} ${response.body}`);
}
log: GET /books
200 The Lighthouse Keeper, A Map of Small Things, Rivers of Glass
log: POST /loans
401 Please sign in
log: POST /loans/1/return
401 Please sign in
log: POST /loans
201 Loan 1: Maya, The Lighthouse Keeper
The third request is refused now, and nobody fixed the return endpoint: it never had the check to forget. The sign-in check is one class, and every request passes it.
The modern version: a middleware is a function
Each step above is a class with one method, and a class with one method can be a function (Pass 1's weekly deal again). So frameworks write a middleware as a function that's handed the request and next, the rest of the line as a function too. A small builder turns a list of them into one pipeline, starting from the endpoint and wrapping each step around it. The inventory weekend is now one more function in the list:
// Each middleware gets the request and next, the rest of the line, and answers or calls next.
Middleware log = (request, next) =>
{
Console.WriteLine( quot;log: {request.Method} {request.Path}");
return next(request);
};
Middleware signIn = (request, next) =>
request.Method != "GET" && request.User == "" ? new Response(401, "Please sign in") : next(request);
Handler pipeline = Build(new List<Middleware> { log, signIn }, Endpoints);
foreach (Request request in new[] { new Request("GET", "/books", ""), new Request("POST", "/loans", ""),
new Request("POST", "/loans/1/return", ""), new Request("POST", "/loans", "Maya") })
{
Response response = pipeline(request);
Console.WriteLine( quot;{response.Status} {response.Body}");
}
// Wraps the steps around the endpoint, last step first, so the first one in the list runs first.
Handler Build(List<Middleware> steps, Handler endpoint)
{
Handler handler = endpoint;
for (int i = steps.Count - 1; i >= 0; i--)
{
Middleware step = steps[i];
Handler next = handler;
handler = request => step(request, next);
}
return handler;
}
Response Endpoints(Request request) => quot;{request.Method} {request.Path}" switch
{
"GET /books" => new Response(200, "The Lighthouse Keeper, A Map of Small Things, Rivers of Glass"),
"POST /loans" => new Response(201, quot;Loan 1: {request.User}, The Lighthouse Keeper"),
"POST /loans/1/return" => new Response(200, "Loan 1 returned: late fee $0.00"),
_ => new Response(404, "No such page"),
};
record Request(string Method, string Path, string User);
record Response(int Status, string Body);
delegate Response Handler(Request request);
delegate Response Middleware(Request request, Handler next);
log: GET /books
200 The Lighthouse Keeper, A Map of Small Things, Rivers of Glass
log: POST /loans
401 Please sign in
log: POST /loans/1/return
401 Please sign in
log: POST /loans
201 Loan 1: Maya, The Lighthouse Keeper
record Request(String method, String path, String user) { }
record Response(int status, String body) { }
interface Handler { Response handle(Request request); }
interface Middleware { Response handle(Request request, Handler next); }
// Wraps the steps around the endpoint, last step first, so the first one in the list runs first.
Handler build(List<Middleware> steps, Handler endpoint) {
Handler handler = endpoint;
for (int i = steps.size() - 1; i >= 0; i--) {
Middleware step = steps.get(i);
Handler next = handler;
handler = request -> step.handle(request, next);
}
return handler;
}
Response endpoints(Request request) {
return switch (request.method() + " " + request.path()) {
case "GET /books" -> new Response(200, "The Lighthouse Keeper, A Map of Small Things, Rivers of Glass");
case "POST /loans" -> new Response(201, "Loan 1: " + request.user() + ", The Lighthouse Keeper");
case "POST /loans/1/return" -> new Response(200, "Loan 1 returned: late fee $0.00");
default -> new Response(404, "No such page");
};
}
void main() {
// Each middleware gets the request and next, the rest of the line, and answers or calls next.
Middleware log = (request, next) -> {
IO.println("log: " + request.method() + " " + request.path());
return next.handle(request);
};
Middleware signIn = (request, next) ->
!request.method().equals("GET") && request.user().isEmpty() ? new Response(401, "Please sign in") : next.handle(request);
Handler pipeline = build(List.of(log, signIn), this::endpoints);
for (Request request : List.of(new Request("GET", "/books", ""), new Request("POST", "/loans", ""),
new Request("POST", "/loans/1/return", ""), new Request("POST", "/loans", "Maya"))) {
Response response = pipeline.handle(request);
IO.println(response.status() + " " + response.body());
}
}
log: GET /books
200 The Lighthouse Keeper, A Map of Small Things, Rivers of Glass
log: POST /loans
401 Please sign in
log: POST /loans/1/return
401 Please sign in
log: POST /loans
201 Loan 1: Maya, The Lighthouse Keeper
from dataclasses import dataclass
@dataclass
class Request:
method: str
path: str
user: str
@dataclass
class Response:
status: int
body: str
# Each middleware gets the request and next, the rest of the line, and answers or calls next.
def log(request, next):
print(f"log: {request.method} {request.path}")
return next(request)
def sign_in(request, next):
if request.method != "GET" and request.user == "":
return Response(401, "Please sign in")
return next(request)
def endpoints(request):
match f"{request.method} {request.path}":
case "GET /books":
return Response(200, "The Lighthouse Keeper, A Map of Small Things, Rivers of Glass")
case "POST /loans":
return Response(201, f"Loan 1: {request.user}, The Lighthouse Keeper")
case "POST /loans/1/return":
return Response(200, "Loan 1 returned: late fee $0.00")
case _:
return Response(404, "No such page")
def build(steps, endpoint):
"""Wraps the steps around the endpoint, last step first, so the first one in the list runs first."""
handler = endpoint
for step in reversed(steps):
handler = (lambda step, next: lambda request: step(request, next))(step, handler)
return handler
pipeline = build([log, sign_in], endpoints)
for request in [Request("GET", "/books", ""), Request("POST", "/loans", ""),
Request("POST", "/loans/1/return", ""), Request("POST", "/loans", "Maya")]:
response = pipeline(request)
print(f"{response.status} {response.body}")
log: GET /books
200 The Lighthouse Keeper, A Map of Small Things, Rivers of Glass
log: POST /loans
401 Please sign in
log: POST /loans/1/return
401 Please sign in
log: POST /loans
201 Loan 1: Maya, The Lighthouse Keeper
// Each middleware gets the request and next, the rest of the line, and answers or calls next.
const log = (request, next) => {
console.log(`log: ${request.method} ${request.path}`);
return next(request);
};
const signIn = (request, next) =>
request.method !== "GET" && request.user === "" ? { status: 401, body: "Please sign in" } : next(request);
function endpoints(request) {
switch (`${request.method} ${request.path}`) {
case "GET /books": return { status: 200, body: "The Lighthouse Keeper, A Map of Small Things, Rivers of Glass" };
case "POST /loans": return { status: 201, body: `Loan 1: ${request.user}, The Lighthouse Keeper` };
case "POST /loans/1/return": return { status: 200, body: "Loan 1 returned: late fee $0.00" };
default: return { status: 404, body: "No such page" };
}
}
// Wraps the steps around the endpoint, last step first, so the first one in the list runs first.
function build(steps, endpoint) {
return steps.reduceRight((next, step) => (request) => step(request, next), endpoint);
}
const pipeline = build([log, signIn], endpoints);
for (const request of [{ method: "GET", path: "/books", user: "" }, { method: "POST", path: "/loans", user: "" },
{ method: "POST", path: "/loans/1/return", user: "" }, { method: "POST", path: "/loans", user: "Maya" }]) {
const response = pipeline(request);
console.log(`${response.status} ${response.body}`);
}
log: GET /books
200 The Lighthouse Keeper, A Map of Small Things, Rivers of Glass
log: POST /loans
401 Please sign in
log: POST /loans/1/return
401 Please sign in
log: POST /loans
201 Loan 1: Maya, The Lighthouse Keeper
interface LibraryRequest { method: string; path: string; user: string; }
interface LibraryResponse { status: number; body: string; }
type Handler = (request: LibraryRequest) => LibraryResponse;
type Middleware = (request: LibraryRequest, next: Handler) => LibraryResponse;
// Each middleware gets the request and next, the rest of the line, and answers or calls next.
const log: Middleware = (request, next) => {
console.log(`log: ${request.method} ${request.path}`);
return next(request);
};
const signIn: Middleware = (request, next) =>
request.method !== "GET" && request.user === "" ? { status: 401, body: "Please sign in" } : next(request);
function endpoints(request: LibraryRequest): LibraryResponse {
switch (`${request.method} ${request.path}`) {
case "GET /books": return { status: 200, body: "The Lighthouse Keeper, A Map of Small Things, Rivers of Glass" };
case "POST /loans": return { status: 201, body: `Loan 1: ${request.user}, The Lighthouse Keeper` };
case "POST /loans/1/return": return { status: 200, body: "Loan 1 returned: late fee $0.00" };
default: return { status: 404, body: "No such page" };
}
}
// Wraps the steps around the endpoint, last step first, so the first one in the list runs first.
function build(steps: Middleware[], endpoint: Handler): Handler {
return steps.reduceRight<Handler>((next, step) => (request) => step(request, next), endpoint);
}
const pipeline = build([log, signIn], endpoints);
const requests: LibraryRequest[] = [{ method: "GET", path: "/books", user: "" }, { method: "POST", path: "/loans", user: "" },
{ method: "POST", path: "/loans/1/return", user: "" }, { method: "POST", path: "/loans", user: "Maya" }];
for (const request of requests) {
const response = pipeline(request);
console.log(`${response.status} ${response.body}`);
}
log: GET /books
200 The Lighthouse Keeper, A Map of Small Things, Rivers of Glass
log: POST /loans
401 Please sign in
log: POST /loans/1/return
401 Please sign in
log: POST /loans
201 Loan 1: Maya, The Lighthouse Keeper
Try it. Add the inventory weekend: a middleware that answers 503 Closed for inventory to anything but GET /books, put between log and signIn in the list. Nothing else changes. Then move it before log, and see what stops being logged.
Where the languages differ. C# names the two shapes with delegates, Java with two one-method interfaces (so any lambda of that shape fits), TypeScript with types, and Python and JavaScript pass functions. JavaScript and TypeScript build the line with reduceRight, which walks the list from its end; Python's build wraps each step in an extra lambda so each one keeps its own next.
Order matters. Each step sees only what the steps before it let through. Logging first means even refused requests are logged; sign-in before the endpoints means no endpoint runs for a stranger. Swap them, and a refused request leaves no line in the log.
Chain of Responsibility, Decorator or middleware?
Middleware borrows from two patterns you've met, which is why it's easy to mix them up:
| Pattern | What it's for | Strengths | Weaknesses | Pick it when |
|---|---|---|---|---|
| Chain of Responsibility | Passing a request along a line of handlers until one handles it or stops it | A handler can be added or removed without touching the others; each one is small | A request can reach the end with nobody handling it; the order is hard to see from inside one handler | Several checks or handlers, any one of which may answer (Pass 3's voice commands) |
| Decorator | Wrapping one object in layers that add a feature, keeping its interface | Features stack in any order without changing the object | Many small wrappers to follow; the order of the layers matters | One object needs extra features, such as a cache and a log on the weather source (Pass 3) |
| Middleware | A line of steps every request passes, each able to answer, pass on, or act on the way back | Jobs that every request needs (logging, sign-in, timing, errors) live in one place each | One slow or wrong step affects every request; the order matters a lot | Every request to an app needs the same checks or wrapping |
Like a chain, any middleware may answer instead of passing the request on. Like a decorator, each one wraps the rest of the line and gets a turn on the way back out, which is how a timing step measures how long the rest took.
Where you've already used it
Every web framework in this pass has a request pipeline. Here is the sign-in check as each one writes it. These aren't run here: each needs its framework's project around it. Versions checked on 2026-11-01.
// ASP.NET Core 10: app.Use adds a middleware; next is the rest of the line.
var app = WebApplication.CreateBuilder(args).Build();
app.Use(async (context, next) =>
{
app.Logger.LogInformation("log: {Method} {Path}", context.Request.Method, context.Request.Path);
await next(context);
});
app.Use(async (context, next) =>
{
if (context.Request.Method != "GET" && context.User.Identity?.IsAuthenticated != true)
{
context.Response.StatusCode = 401;
await context.Response.WriteAsync("Please sign in");
return;
}
await next(context);
});
app.MapGet("/books", () => "The Lighthouse Keeper, A Map of Small Things, Rivers of Glass");
app.Run();
// Spring Boot 4.1: a servlet filter is Spring's middleware; chain.doFilter passes the request on.
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
@Component
public class SignInFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
if (!request.getMethod().equals("GET") && request.getUserPrincipal() == null) {
response.setStatus(401);
response.getWriter().write("Please sign in");
return;
}
chain.doFilter(request, response);
}
}
# FastAPI 0.162: @app.middleware("http") adds a middleware; call_next is the rest of the line.
from fastapi import FastAPI, Request
from fastapi.responses import PlainTextResponse
app = FastAPI()
@app.middleware("http")
async def sign_in_check(request: Request, call_next):
if request.method != "GET" and "authorization" not in request.headers:
return PlainTextResponse("Please sign in", status_code=401)
return await call_next(request)
// Express 5.3: app.use adds a middleware; next() passes the request on.
import express from "express";
const app = express();
app.use((req, res, next) => {
console.log(`log: ${req.method} ${req.path}`);
next();
});
app.use((req, res, next) => {
if (req.method !== "GET" && !req.get("authorization")) {
return res.status(401).send("Please sign in");
}
next();
});
app.get("/books", (req, res) => res.send("The Lighthouse Keeper, A Map of Small Things, Rivers of Glass"));
app.listen(3000);
// NestJS 12.3 (on Express): a middleware class with use(req, res, next); next() passes it on.
import { Injectable, type NestMiddleware } from "@nestjs/common";
import type { NextFunction, Request, Response } from "express";
@Injectable()
export class SignInMiddleware implements NestMiddleware {
use(req: Request, res: Response, next: NextFunction): void {
if (req.method !== "GET" && !req.headers.authorization) {
res.status(401).send("Please sign in");
return;
}
next();
}
}
Every one of them is "handed the request and the rest of the line; answer, or pass it on".
When not to use it
- For a check only one endpoint needs. A rule about returning books belongs in the return endpoint (or the checkout service), not in a step every request pays for.
- For the library's rules. Middleware is for jobs about requests (who's asking, how long it took, what went wrong). Late fees and the five-book limit belong in the model.
- When the line gets long and clever. Twenty steps that depend on each other's order, each changing the request a little, are hard to follow. Keep each step small, and write down why the order is what it is.
How often you'll meet it: every day in web back ends (our estimate).
Check yourself
2 questions to try on the lesson page.
So what
When every endpoint starts with the same checks, one of them will forget one. Give each check its own small step in a line every request passes through, and the endpoints keep only their own work. That line is the request pipeline, and it's the first thing to look for in any web framework you're new to.