Skip to content

Type Alias: MiddlewareFn()<TContext>

ts
type MiddlewareFn<TContext> = (ctx, args, next) => Promise<unknown>;

Defined in: packages/core/src/core/types.ts:244

Middleware function signature.

Follows the next() pattern (similar to Express/Koa). Middleware can inspect/modify args, short-circuit with an error, or wrap the handler with cross-cutting concerns.

Middleware chains are pre-compiled at build time — there is zero chain assembly or closure allocation per request.

Type Parameters

Type ParameterDescription
TContextApplication context

Parameters

ParameterType
ctxTContext
argsRecord<string, unknown>
next() => Promise<unknown>

Returns

Promise<unknown>

Example

typescript
// Authentication middleware
const requireAuth: MiddlewareFn<AppContext> = async (ctx, args, next) => {
    if (!ctx.user) return error('Unauthorized');
    return next();
};

// Logging middleware
const logger: MiddlewareFn<AppContext> = async (ctx, args, next) => {
    const start = Date.now();
    const result = await next();
    console.log(`${args.action} took ${Date.now() - start}ms`);
    return result;
};

// Apply to a builder
const builder = new GroupedToolBuilder<AppContext>('projects')
    .use(logger)        // Global: runs on every action
    .use(requireAuth);  // Global: runs after logger

See