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
ruby
module RequestTagging class Middleware def initialize(app) @app = app
Per-request context with CurrentAttributes in Rails
middleware
thread-safety
logging
Intermediate
7 steps
go
package middleware import ( "net/http"
Wrapping Gin requests in a DB transaction
middleware
transactions
error-handling
Intermediate
8 steps
php
<?php namespace App\Http\Middleware;
Caching HTTP responses with Laravel middleware
middleware
caching
http
Intermediate
8 steps
typescript
type Countdown = { days: number; hours: number; minutes: number;
Building a self-stopping countdown timer
date-math
closures
timers
Intermediate
9 steps
java
import java.util.HashSet; import java.util.Set; public final class CollectionDiff<T> {
Diffing two collections with set operations
set-operations
immutability
generics
Intermediate
8 steps
typescript
export function isValidCardNumber(input: string): boolean { const digits = input.replace(/[\s-]/g, ""); if (!/^\d{12,19}$/.test(digits)) {
Validating card numbers with the Luhn check
luhn-algorithm
checksum
input-validation
Intermediate
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.