Middlewares
Problem statement
Implement a middlewares function that takes any number of middleware functions and composes them into a single callable function.
The composed function accepts a shared context, returns a Promise, and calls each middleware in order. The behavior should be similar to Koa middleware.
Middleware Shape
async function middleware(context, next) {
// read or mutate context
await next();
}
Rules
- Each middleware receives
contextandnext. - Calling
next()invokes the next middleware. - If a middleware does not call
next(), the chain stops. - Execution must be asynchronous and sequential.
- Calling
next()more than once should reject with an error.
Requirements & constraints
- Return a Promise from the composed function.
- Support async and sync middlewares.
- Reject if `next()` is called more than once by the same chain step.
How to approach Middlewares
The strategy an interviewer expects you to reach for.
Middleware composition is Koa/Express style: each layer gets (context, next) and chooses when to continue the chain. Naive move Call every middleware in a for-loop without a next callback. You lose before/after semantics and short-circuiting. Where it breaks Calling next() twice must error. Falling off the end should resolve. Async middleware must be thenable-aware. The fix Dispatch by index. Guard i <= index to detect double next. next calls dispatch(i+1). Wrap return values in Promise.resolve. Remember: next is a single-step forward cursor — double-call is a hard error. Say this in the interview: I'd compose middleware with an index dispatcher, reject if next is called twice, and let each layer await next() for downstream work.
The full solution is part of HelloFrontend Pro
The question above is free to read in full. Upgrade to unlock the interactive workspace and the senior-level walkthrough that go with it.
- Runnable editor with the hidden test suite
- Progressive hints that unlock as you get stuck
- Senior-level reference solution with a line-by-line walkthrough
Already a member? Log in to open the workspace.