Course contentsShow
← TypeScript
Lesson 597 of 1,79614. Generics in PracticeFree lesson

Generic Middleware and Pipeline Composition

Type request/response flows where handlers transform generic context types through a chain.

Generic Middleware and Pipeline Composition

What You'll Learn: How to type request/response flows where each middleware handler transforms a generic context type as it passes through a chain.

The Core Idea

Imagine a factory assembly line: raw materials enter, each station adds or transforms something, and a finished product emerges. Middleware pipelines work the same way—a request enters, each handler enriches or modifies a shared context object, and a final response exits.

The challenge is typing this flow so TypeScript knows what properties exist at each stage. Generics let you describe how each middleware transforms the context type, ensuring type safety throughout the entire chain.

How It Works

Each middleware function is generic over the context type it receives and the type it produces after transformation:

type Middleware<TIn, TOut> = (context: TIn) => TOut;

// Start with a basic context
type BaseContext = { request: string };

// First middleware adds userId
const addAuth: Middleware<BaseContext, BaseContext & { userId: number }> = 
  (ctx) => ({ ...ctx, userId: 42 });

// Second middleware adds permissions
const addPerms: Middleware<
  BaseContext & { userId: number }, 
  BaseContext & { userId: number; permissions: string[] }
> = (ctx) => ({ ...ctx, permissions: ['read', 'write'] });

// Compose the pipeline
function compose(ctx: BaseContext) {
  const withAuth = addAuth(ctx);
  const withPerms = addPerms(withAuth);
  return withPerms;
}

const result = compose({ request: 'GET /api' });
// result has type: { request: string; userId: number; permissions: string[] }

Each middleware's output type becomes the next one's input type. TypeScript tracks what's available at every step, preventing you from accessing properties before they exist.

Key Takeaway: Generic middleware types let you model transformation pipelines where each handler enriches a context type, giving you compile-time guarantees about what data exists at each stage of the chain.