Middleware
Middleware run before or after your controller method, depending on the phase where you register them. They receive the native request/response types of the adapter you use.
interface Middleware<
  TRequest = any,
  TResponse = any,
  TNextFunction = any,
  TResult = any,
> {
  execute(
    request: TRequest,
    response: TResponse,
    next: TNextFunction,
  ): Promise<TResult> | TResult;
}
Specific adapters use their own request/response types:
- Express 4
- Express 5
- Fastify
- Hono
type ExpressMiddleware = Middleware<
  express.Request,
  express.Response,
  express.NextFunction,
  void
>;
type ExpressMiddleware = Middleware<
  express.Request,
  express.Response,
  express.NextFunction,
  void
>;
type FastifyMiddleware = Middleware<
  FastifyRequest,
  FastifyReply,
  HookHandlerDoneFunction,
  void
>;
type HonoMiddleware = Middleware<
  HonoRequest,
  Context,
  Next,
  Response | undefined
>;
execute
Handles the request and response objects. Use it to modify them or perform actions before passing control to the next middleware or the route handler.
Adapter-specific examples
Each adapter exposes its own request/response types. Here is the same middleware that sets a custom header for each adapter.
- Express 4
- Express 5
- Fastify
- Hono
export class Express4CustomHeaderMiddleware implements ExpressMiddleware {
  public execute(
    _request: Request,
    response: Response,
    next: NextFunction,
  ): void {
    response.setHeader('custom-header', 'value');
    next();
  }
}
export class ExpressCustomHeaderMiddleware implements ExpressMiddleware {
  public execute(
    _request: Request,
    response: Response,
    next: NextFunction,
  ): void {
    response.setHeader('custom-header', 'value');
    next();
  }
}
export class FastifyCustomHeaderMiddleware implements FastifyMiddleware {
  public execute(
    _request: FastifyRequest,
    response: FastifyReply,
    next: HookHandlerDoneFunction,
  ): void {
    response.header('custom-header', 'value');
    next();
  }
}
export class HonoCustomHeaderMiddleware implements HonoMiddleware {
  public async execute(
    _request: HonoRequest,
    response: Context,
    next: Next,
  ): Promise<Response | undefined> {
    response.header('custom-header', 'value');
    await next();
    return undefined;
  }
}
If you are implementing a post handler middleware in Hono, the adapter already calls next() for you after the middleware execution. Do not call it again in your middleware implementation, or an Internal Server Error will occur.
Attaching middleware
Use the ApplyMiddleware decorator at the controller level (applies to all routes) or at the method level (applies to one route).
Global middleware can be registered using the InversifyHttpAdapter.