Middleware Compose With Types
Compose middleware functions with proper typing for request pipeline processing in web frameworks.
Code
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<=indexshort-circuits the flow with an earlythrowwhen 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
Docker Run to Compose ConverterTransform docker run CLI commands with ports, environment variables, volumes, networks, and resource limits into clean compose.yaml service definitions.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.