BeginnerCoder

Lesson 23 — Middleware compose

A chain of handlers

In Express and Koa, a request passes through middleware: small functions that each do one job (log, check login, parse JSON) and then call next() to hand over to the next one. Code after next() runs on the way back, like layers of an onion.

compose turns a list of middleware into one function. dispatch(i) runs middleware number i and gives it a next that calls dispatch(i + 1).

Note: this playground runs JavaScript in your browser, not in real Node, so Node-only tools (like fs or http) are not available. The exercise is a small plain-JS simulation of the Node idea.

Why it matters: this is how almost every Node web framework structures a request.

Want it another way?
Task

Finish dispatch(): if middleware i exists, call it with ctx and a next function that runs middleware i + 1.

Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.

← Back
Next →
Test your knowledge

A quick 3-question quiz on this lesson — instant feedback.

Enjoying this lesson? Share it.

Keep going with Node.js Foundations

Ready for more? Optional paid resources that pick up where this lesson leaves off.

Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.