Generic Middleware Composition
What you'll learn: How to use generics to build type-safe middleware pipelines that track how each middleware transforms the context type.
The Core Idea
Middleware is a common pattern where you chain functions together, each potentially modifying a shared context before passing it to the next function. In frameworks like Express, Koa, or custom pipelines, each middleware might add properties to a request object or context.
The challenge: Without generics, you lose track of what properties exist at each stage. With generics, you can make TypeScript understand that each middleware transforms the context type, ensuring the final composed result has the correct type.
How Generics Track Context Transformations
Think of middleware composition like an assembly line. Each station (middleware) receives a product (context), potentially adds features to it, and passes it along. Generics let you describe what each station adds:
type Middleware<TInput, TOutput> = (ctx: TInput) => TOutput;
function compose<A, B, C>(
first: Middleware<A, B>,
second: Middleware<B, C>
): Middleware<A, C> {
return (ctx: A) => second(first(ctx));
}
// Usage
type BaseContext = { requestId: string };
type WithUser = BaseContext & { userId: number };
type WithAuth = WithUser & { isAdmin: boolean };
const addUser: Middleware<BaseContext, WithUser> =
(ctx) => ({ ...ctx, userId: 42 });
const addAuth: Middleware<WithUser, WithAuth> =
(ctx) => ({ ...ctx, isAdmin: true });
const pipeline = compose(addUser, addAuth);
// Type: Middleware<BaseContext, WithAuth>
const result = pipeline({ requestId: "abc" });
// result has: requestId, userId, isAdmin ✓
Each middleware's output type becomes the next middleware's input type, creating a type-safe chain.
Key Takeaway: Generic middleware composition uses type parameters to track how context flows and transforms through a pipeline, ensuring type safety at every step and in the final result.