Skip to content

middleware

Generated reference page for the middleware function export.

Signatures

ts
function middleware<Output extends Record<string, unknown>>(handler: MiddlewareHandler<Output>): Middleware<Output>;
ParameterTypeDescription
handlerMiddlewareHandler<Output>Function receiving { args, flags, ctx, out, meta, next }.
Call next(additions) to continue the chain with added context.
Omitting the next() call short-circuits (e.g., for auth guards).

Members

Members

middleware

Create a middleware definition.

Middleware runs before the action handler and can add typed context, short-circuit execution, or wrap downstream processing.

ts
(handler: MiddlewareHandler<Output>): Middleware<Output>;

Examples

ts
// Auth guard — adds user to context or throws
const auth = middleware(async ({ next }) => {
  const user = await getUser();
  if (!user) throw new CLIError('Not authenticated', { code: 'AUTH_REQUIRED' });
  return next({ user });
});

// Timing wrapper — measures downstream execution
const timing = middleware(async ({ out, next }) => {
  const start = Date.now();
  await next({});
  out.info(`Done in ${Date.now() - start}ms`);
});

command('deploy')
  .middleware(timing)
  .middleware(auth)
  .action(({ ctx }) => {
    console.log(ctx.user.name); // typed!
  });

See Also

Released under the MIT License.