Skip to main content
Version: Next

+middleware.ts

The src/app/commands/+middleware.ts (or +middleware.js) file is used to define middleware functions for your application. Middleware functions are functions that execute before and after the command execution.

src/app/commands/+middleware.ts
import { MiddlewareContext } from 'commandkit';

export function beforeExecute(context: MiddlewareContext) {
// This function will be executed before the command is executed
console.log('Before command execution');
}

export function afterExecute(context: MiddlewareContext) {
// This function will be executed after the command is executed
console.log('After command execution');
}

There are 3 types of middleware files you can create:

  • +middleware.ts (or +middleware.js): This file is used to define middleware functions that will be executed for all sibling commands in the application.
  • +middleware.<command>.ts (or +middleware.<command>.js): This file is used to define middleware functions that will be executed for a specific command in the application. The <command> part of the filename should match the name of the command file.
  • +global-middleware.ts (or +global-middleware.js): This file is used to define middleware functions that will be executed for all commands in the application, regardless of their location in the file system. This is useful for defining global middleware functions that should be applied to all commands.

The code pattern is same for all middleware types.