Skip to content

Function: defineMiddleware()

ts
function defineMiddleware<TContextIn, TDerived>(derive): MiddlewareDefinition<TContextIn, TDerived>;

Defined in: packages/core/src/core/middleware/ContextDerivation.ts:123

Define a context-deriving middleware.

The returned object can be used in two ways:

  1. As a type-level constraint (the generics carry the derived context)
  2. As a runtime middleware via .toMiddlewareFn() (for the existing pipeline)

Type Parameters

Type ParameterDescription
TContextInThe input context type
TDerived extends Record<string, unknown>Auto-inferred derived properties

Parameters

ParameterTypeDescription
derive(ctx) => TDerived | Promise<TDerived>Function that inspects context and returns derived data

Returns

MiddlewareDefinition<TContextIn, TDerived>

A MiddlewareDefinition with the derived type encoded

Example

typescript
// Auth middleware that derives `user`
const requireAuth = defineMiddleware(async (ctx: { token: string }) => {
    const user = await db.getUser(ctx.token);
    if (!user) throw new Error('Unauthorized');
    return { user };
});

// Rate limit middleware that derives `rateLimitInfo`
const rateLimit = defineMiddleware(async (ctx: { ip: string }) => {
    const info = await checkRateLimit(ctx.ip);
    if (info.exceeded) throw new Error('Rate limited');
    return { rateLimitInfo: info };
});

See

MiddlewareFn for the standard middleware type