Middleware Compose With Types

Compose middleware functions with proper typing for request pipeline processing in web frameworks.

TypescriptCli Tooling

Code

typescriptsnippet
1 line
type Context=Record<string,unknown>;type Next=()=>Promise<void>;type Middleware=(ctx:Context,next:Next)=>Promise<void>;export function compose(...middlewares:Middleware[]):Middleware{return async function(ctx,next){let index=-1;async function dispatch(i:number):Promise<void>{if(i<=index)throw new Error('next() called multiple times');index=i;const fn=middlewares[i];if(!fn)return next();await fn(ctx,()=>dispatch(i+1));}await dispatch(0);};}

How it works

Middleware Compose With Types comes down to the functions compose and dispatch.

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. Failure is loud: Error aborts the current operation instead of degrading it.

What to watch for

  • The guard i<=index short-circuits the flow with an early throw when its condition holds.

Putting it to use

The main signature reads export function compose(...middlewares:Middleware[])

compose is what another module would consume; nothing else here is load-bearing for callers.

Interactive Tools for This Topic

FAQ

What does the snippet do with malformed data?
It throws `Error` before any real work runs, via the guard `i<=index` — handle it at the call site or let it propagate deliberately.
Is there an install step between copy and run?
No. Between copying and running there is nothing left to do. The file defines `compose`, `dispatch` at load time.