typescript
47 lines · 9 steps
A type-safe async middleware pipeline
How TypeScript generics thread the output type of each middleware into the input of the next to build a fully-typed request pipeline.
Explained by
highlit
1type Middleware<TIn, TOut> = (ctx: TIn) => Promise<TOut> | TOut;
2
3class Pipeline<TIn, TOut> {
4 private constructor(private readonly run: Middleware<TIn, TOut>) {}
5
6 static create<T>(): Pipeline<T, T> {
7 return new Pipeline<T, T>((ctx) => ctx);
8 }
9
10 pipe<TNext>(next: Middleware<TOut, TNext>): Pipeline<TIn, TNext> {
11 return new Pipeline<TIn, TNext>(async (ctx) => next(await this.run(ctx)));
12 }
13
14 execute(ctx: TIn): Promise<TOut> {
15 return Promise.resolve(this.run(ctx));
16 }
17}
18
19interface RawRequest {
20 headers: Record<string, string>;
21 body: string;
22}
23
24interface AuthedRequest extends RawRequest {
25 userId: string;
26}
27
28interface ParsedRequest<T> extends AuthedRequest {
29 payload: T;
30}
31
32const authenticate: Middleware<RawRequest, AuthedRequest> = (req) => {
33 const token = req.headers["authorization"]?.replace(/^Bearer /, "");
34 if (!token) throw new Error("missing authorization header");
35 return { ...req, userId: verifyToken(token) };
36};
37
38const parseBody = <T>(): Middleware<AuthedRequest, ParsedRequest<T>> => (req) => {
39 if (!req.headers["content-type"]?.includes("application/json")) {
40 throw new Error("expected application/json");
41 }
42 return { ...req, payload: JSON.parse(req.body) as T };
43};
44
45export const requestPipeline = Pipeline.create<RawRequest>()
46 .pipe(authenticate)
47 .pipe(parseBody<{ orderId: string; quantity: number }>());
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Threading two type parameters through a chain lets the compiler guarantee each stage's input matches the previous stage's output.
- 2Wrapping the composition in a new immutable instance keeps each pipe step pure and reusable.
- 3Accepting Promise<T> | T and normalizing with Promise.resolve lets sync and async middleware coexist seamlessly.
Related explainers
typescript
import { registerLocaleData } from '@angular/common'; import localeFr from '@angular/common/locales/fr'; import localeFrExtra from '@angular/common/locales/extra/fr'; import localeDe from '@angular/common/locales/de';
Locale-aware bootstrapping in Angular
i18n
localization
dependency-injection
Intermediate
8 steps
python
from fastapi import FastAPI, WebSocket, WebSocketDisconnect app = FastAPI()
Building a WebSocket chat with FastAPI
websockets
broadcast
connection-management
Intermediate
9 steps
typescript
import { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; import * as Joi from 'joi';
Validating env config at boot in NestJS
configuration
schema-validation
environment-variables
Intermediate
8 steps
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
typescript
import { Inject, Injectable, Logger } from '@nestjs/common'; import { CACHE_MANAGER } from '@nestjs/cache-manager'; import { Cache } from 'cache-manager'; import { InjectRepository } from '@nestjs/typeorm';
A cache-aside country lookup in NestJS
cache-aside
dependency-injection
batch-lookup
Intermediate
8 steps
rust
use axum::{ extract::{Path, State}, response::sse::{Event, KeepAlive, Sse}, };
Streaming import progress with SSE in Axum
server-sent-events
streams
watch-channel
Advanced
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/a-type-safe-async-middleware-pipeline-explained-typescript-6f6d/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.