Decorators
This section covers Inversify HTTP decorators used to provide related metadata.
Many decorators in this framework accept ServiceIdentifier types for dependency injection. A ServiceIdentifier<T> can be:
- A class constructor (e.g., MyMiddleware)
- A string token (e.g., 'my-middleware')
- A symbol (e.g., Symbol.for('my-middleware'))
- An abstract class reference
This allows for flexible dependency resolution through the InversifyJS container.
HTTP Request lifecycle
Inversify HTTP decorators can be used to manage the lifecycle of HTTP requests, including middleware execution, request handling, and response generation. This allows for more modular and maintainable code.
ApplyMiddleware
Attaches middleware to a controller class (applies to all its routes) or to a specific route method.
ApplyMiddleware(
  ...middlewareList: (ServiceIdentifier<Middleware> | ApplyMiddlewareOptions)[],
): ClassDecorator & MethodDecorator
Parameters
- middlewareList: One or more middleware service identifiers or options objects.- ServiceIdentifier<Middleware>: A middleware class, string token, symbol, or abstract class that can be resolved by the DI container.
- ApplyMiddlewareOptions: Configuration object with middleware and phase settings.
 
Notes
- Scope: Place the decorator on the controller class to affect all routes, or on a method to affect only that route.
- Phase: When passing middleware service identifiers directly (not the options object), they run in the PreHandlerphase by default.
- Order: Within the same phase, middleware execute in the order they are provided.
- See also: Middleware fundamentals for adapter-specific request/response types and tips.
Example: apply middleware to a controller (all routes)
@ApplyMiddleware(MyMiddleware)
@Controller('/ping')
class PingController {
  @Get()
  public async get(): Promise<string> {
    return 'pong';
  }
}
Example: apply middleware to a single route
@Controller('/ping')
class PingController {
  @ApplyMiddleware(MyMiddleware)
  @Get()
  public async get(): Promise<string> {
    return 'pong';
  }
}
Next
Injects the framework-specific next function into your controller method. Call it to continue a pipeline. For example, a middleware can run first (e.g., to set headers), then your controller can return the response.
Next(): ParameterDecorator
Example: calling next per adapter
- Express 4
- Express 5
- Fastify
- Hono
@Controller('/next')
export class NextExpress4Controller {
  @UseInterceptor(Express4NextInterceptor)
  @Get()
  public getNext(@Next() next: NextFunction): void {
    next();
  }
}
@Controller('/next')
@UseInterceptor(ExpressNextInterceptor)
export class NextExpressController {
  @Get()
  public getNext(@Next() next: NextFunction): void {
    next();
  }
}
@Controller('/next')
@UseInterceptor(FastifyNextInterceptor)
export class NextFastifyController {
  @Get()
  public getNext(@Next() next: HookHandlerDoneFunction): void {
    next();
  }
}
@Controller('/next')
export class NextHonoController {
  @UseInterceptor(HonoNextInterceptor)
  @Get()
  public async getNext(@Next() next: HonoNext): Promise<void> {
    await next();
  }
}
UseErrorFilter
Attaches one or more error filters to a controller class or method. Error filters handle exceptions that occur during request processing.
UseErrorFilter(...errorFilterList: Newable<ErrorFilter>[]): ClassDecorator & MethodDecorator
Parameters
- errorFilterList: One or more error filter classes implementing- ErrorFilter.
Notes
- Scope: Place on the controller class to affect all routes, or on a method to affect only that route.
- Order: Error filters are processed in the order they are provided.
- Exception handling: Error filters can catch, transform, or handle exceptions thrown during request processing.
UseGuard
Attaches one or more guards to a controller class or method. All guards must allow for the request to continue.
UseGuard(...guardList: ServiceIdentifier<Guard>[]): ClassDecorator & MethodDecorator
Parameters
- guardList: One or more guard service identifiers that can be resolved by the DI container.
UseInterceptor
Attaches one or more interceptors to a controller class or method. Interceptors can modify requests before they reach the handler and responses before they are sent.
UseInterceptor(...interceptorList: ServiceIdentifier<Interceptor>[]): ClassDecorator & MethodDecorator
Parameters
- interceptorList: One or more interceptor service identifiers that can be resolved by the DI container.
HTTP Request message abstraction
Inversify HTTP decorators can be used to abstract HTTP request details, such as headers, query parameters, and request bodies. This allows for cleaner controller code and better separation of concerns.
Body
Reads the HTTP request body, or a specific property of it when a name is provided.
Body(
  optionsOrPipe?: RouteParameterOptions | (ServiceIdentifier<Pipe> | Pipe),
  ...parameterPipeList: (ServiceIdentifier<Pipe> | Pipe)[]
): ParameterDecorator
Parameters
- optionsOrPipe(optional): Either route parameter options or a pipe. When this is- RouteParameterOptions, it contains configuration like- parameterName. When it's a pipe (service identifier or instance), it's the first pipe in the pipeline.
- parameterPipeList: Additional pipes to apply to the parameter for transformation and validation.
Example: reading a request body
@Controller('/messages')
export class BodyController {
  @Post()
  public async createMessage(@Body() body: BodyPayload): Promise<BodyResult> {
    return {
      message: body.message,
    };
  }
}
Headers
Reads HTTP request headers, or a specific header when a name is provided.
Headers(
  optionsOrPipe?: RouteParameterOptions | (ServiceIdentifier<Pipe> | Pipe),
  ...parameterPipeList: (ServiceIdentifier<Pipe> | Pipe)[]
): ParameterDecorator
Parameters
- optionsOrPipe(optional): Either route parameter options or a pipe. When this is- RouteParameterOptions, it contains configuration like header- name. When it's a pipe (service identifier or instance), it's the first pipe in the pipeline.
- parameterPipeList: Additional pipes to apply to the parameter for transformation and validation.
Example: reading the User-Agent header
@Controller('/headers')
export class HeadersController {
  @Get()
  public async getUserAgent(
    @Headers({
      name: 'x-client',
    })
    userAgent: string | undefined,
  ): Promise<HeadersResult> {
    return {
      agent: userAgent,
    };
  }
}
Cookies
Reads HTTP cookies, or a specific cookie when a name is provided.
Remember to enable useCookies option when using express or fastify adapters.
Cookies(
  optionsOrPipe?: RouteParameterOptions | (ServiceIdentifier<Pipe> | Pipe),
  ...parameterPipeList: (ServiceIdentifier<Pipe> | Pipe)[]
): ParameterDecorator
Parameters
- optionsOrPipe(optional): Either route parameter options or a pipe. When this is- RouteParameterOptions, it contains configuration like cookie- name. When it's a pipe (service identifier or instance), it's the first pipe in the pipeline.
- parameterPipeList: Additional pipes to apply to the parameter for transformation and validation.
Example: reading a session cookie
@Controller('/cookies')
export class CookiesController {
  @Get()
  public async getCookie(
    @Cookies({
      name: 'sessionId',
    })
    sessionId: string | undefined,
  ): Promise<CookiesResult> {
    return {
      sessionId,
    };
  }
}
Params
Reads HTTP route parameters (path parameters), or a specific parameter when a name is provided.
Params(
  optionsOrPipe?: RouteParameterOptions | (ServiceIdentifier<Pipe> | Pipe),
  ...parameterPipeList: (ServiceIdentifier<Pipe> | Pipe)[]
): ParameterDecorator
Parameters
- optionsOrPipe(optional): Either route parameter options or a pipe. When this is- RouteParameterOptions, it contains configuration like parameter- name. When it's a pipe (service identifier or instance), it's the first pipe in the pipeline.
- parameterPipeList: Additional pipes to apply to the parameter for transformation and validation.
Request
Retrieves the native request object of the current adapter. Useful when you need full access to the underlying framework request.
Request(...pipeList: (ServiceIdentifier<Pipe> | Pipe)[]): ParameterDecorator
Example: accessing the native request per adapter
- Express 4
- Express 5
- Fastify
- Hono
@Controller('/headers')
export class RequestExpressController {
  @Get()
  public async readHeader(
    @Request() request: express.Request,
  ): Promise<string> {
    const value: string | string[] | undefined =
      request.headers['x-test-header'];
    let parsedValue: string;
    if (Array.isArray(value)) {
      if (value.length !== 1) {
        throw new BadRequestHttpResponse(
          'Expected a single `x-test-header` value',
        );
      }
      [parsedValue] = value as [string];
    } else {
      parsedValue = value ?? '';
    }
    return parsedValue;
  }
}
@Controller('/headers')
export class RequestExpressController {
  @Get()
  public async readHeader(
    @Request() request: express.Request,
  ): Promise<string> {
    const value: string | string[] | undefined =
      request.headers['x-test-header'];
    let parsedValue: string;
    if (Array.isArray(value)) {
      if (value.length !== 1) {
        throw new BadRequestHttpResponse(
          'Expected a single `x-test-header` value',
        );
      }
      [parsedValue] = value as [string];
    } else {
      parsedValue = value ?? '';
    }
    return parsedValue;
  }
}
@Controller('/headers')
export class RequestFastifyController {
  @Get()
  public async readHeader(@Request() request: FastifyRequest): Promise<string> {
    const value: string | string[] | undefined =
      request.headers['x-test-header'];
    let parsedValue: string;
    if (Array.isArray(value)) {
      if (value.length !== 1) {
        throw new BadRequestHttpResponse(
          'Expected a single `x-test-header` value',
        );
      }
      [parsedValue] = value as [string];
    } else {
      parsedValue = value ?? '';
    }
    return parsedValue;
  }
}
@Controller('/headers')
export class RequestHonoController {
  @Get()
  public async readHeader(@Request() request: HonoRequest): Promise<string> {
    const value: string | undefined = request.header('x-test-header');
    return value ?? '';
  }
}
Query
Reads HTTP query parameters, or a specific query parameter when a name is provided.
Query(
  optionsOrPipe?: RouteParameterOptions | (ServiceIdentifier<Pipe> | Pipe),
  ...parameterPipeList: (ServiceIdentifier<Pipe> | Pipe)[]
): ParameterDecorator
Parameters
- optionsOrPipe(optional): Either route parameter options or a pipe. When this is- RouteParameterOptions, it contains configuration like parameter- name. When it's a pipe (service identifier or instance), it's the first pipe in the pipeline.
- parameterPipeList: Additional pipes to apply to the parameter for transformation and validation.
HTTP Response message abstraction
Inversify HTTP decorators can also be used to abstract HTTP response details, such as status codes and headers. This allows for more consistent and maintainable response handling across controllers.
Response
Injects the native response object of the current adapter. Use it when you want to write directly to the underlying framework response.
Response(...pipeList: (ServiceIdentifier<Pipe> | Pipe)[]): ParameterDecorator
Notes
- Type-safe: Type the parameter with the adapter's response type for intellisense and safety.
- Return type: When you write to the native response, prefer a return type of void. For Hono, return theResponseproduced by theContext.
- Hono: Prefer using @Context()from@inversifyjs/http-honoto access Hono'sContextobject.
Example: sending a response per adapter
- Express 4
- Express 5
- Fastify
- Hono
@Controller('/message')
export class ResponseExpressController {
  @Get()
  public async sendMessage(
    @Response() response: express.Response,
  ): Promise<void> {
    response.send({ message: 'hello' });
  }
}
@Controller('/message')
export class ResponseExpressController {
  @Get()
  public async sendMessage(
    @Response() response: express.Response,
  ): Promise<void> {
    response.send({ message: 'hello' });
  }
}
@Controller('/message')
export class ResponseFastifyController {
  @Get()
  public async sendMessage(@Response() reply: FastifyReply): Promise<void> {
    reply.send({ message: 'hello' });
  }
}
@inversifyjs/http-hono provides the @Context() decorator to access the Context object.
import { Controller, Get } from '@inversifyjs/http-core';
import { Context } from '@inversifyjs/http-hono';
import { type Context as HonoContext } from 'hono';
@Controller('/message')
export class ResponseHonoController {
  @Get()
  public async sendMessage(@Context() context: HonoContext): Promise<Response> {
    return context.json({ message: 'hello' });
  }
}
SetHeader
Sets a HTTP response header.
SetHeader(headerKey: string, value: string): MethodDecorator
Parameters
- headerKey(string): Name of the header to be set.
- value(string): Value of the header to be set.
Example: Setting a response header
@Controller('/messages')
export class ContentController {
  @Post()
  @SetHeader('custom-content-header', 'sample')
  public async createMessage(@Body() body: BodyPayload): Promise<BodyResult> {
    return {
      message: body.message,
    };
  }
}
StatusCode
Sets the HTTP response status code.
StatusCode(statusCode: HttpStatusCode): MethodDecorator
Parameters
- statusCode(HttpStatusCode): Status code to be set.
Example: Setting a response status code
@Controller('/messages')
export class ContentController {
  @Post()
  @StatusCode(HttpStatusCode.CREATED)
  public async createMessage(@Body() body: BodyPayload): Promise<BodyResult> {
    return {
      message: body.message,
    };
  }
}
HTTP methods
All
Sets up a route for all HTTP methods.
All(path?: string): MethodDecorator
Parameters
- path(optional string): Route path mounted under the controller's base path. Defaults to- '/'. It binds the method to all HTTP methods for the given path.
Example: decorating a controller method
@Controller('/content')
export class ContentController {
  @All()
  public async allContent(): Promise<void> {}
}
Delete
Sets up a route for DELETE requests.
Delete(path?: string): MethodDecorator
Parameters
- path(optional string): Route path mounted under the controller's base path. Defaults to- '/'. Example:- @Delete('/remove')maps to- DELETE <controllerPath>/remove.
Example: decorating a controller method
@Controller('/content')
export class ContentController {
  @Delete()
  public async deleteContent(
    @Query() queryParams: { content: string },
  ): Promise<Content> {
    return {
      content: queryParams.content,
    };
  }
}
Get
Sets up a route for GET requests.
Get(path?: string): MethodDecorator
Parameters
- path(optional string): Route path mounted under the controller's base path. Defaults to- '/'. Example:- @Get('/list')maps to- GET <controllerPath>/list. When omitted, the method is bound to the controller path itself.
Example: decorating a controller method
@Controller('/content')
export class ContentController {
  @Get()
  public async getContent(
    @Query() queryParams: { content: string },
  ): Promise<Content> {
    return {
      content: queryParams.content,
    };
  }
}
Head
Sets up a route for HEAD requests.
Since hono@4, HEAD routes are no longer allowed, use @Get routes instead if you rely on the Hono adapter.
Head(path?: string): MethodDecorator
Parameters
- path(optional string): Route path mounted under the controller's base path. Defaults to- '/'. Example:- @Head('/')maps to- HEAD <controllerPath>.
Example: decorating a controller method
@Controller('/content')
export class ContentController {
  @Head()
  @SetHeader('custom-content-header', 'sample')
  public async headContent(): Promise<undefined> {
    return undefined;
  }
}
Options
Sets up a route for OPTIONS requests.
Options(path?: string): MethodDecorator
Parameters
- path(optional string): Route path mounted under the controller's base path. Defaults to- '/'. Example:- @Options('/')maps to- OPTIONS <controllerPath>.
Example: decorating a controller method
@Controller('/content')
export class ContentController {
  @Options()
  public async optionsContent(): Promise<undefined> {
    return undefined;
  }
}
Patch
Sets up a route for PATCH requests.
Patch(path?: string): MethodDecorator
Parameters
- path(optional string): Route path mounted under the controller's base path. Defaults to- '/'. Example:- @Patch('/partial')maps to- PATCH <controllerPath>/partial.
Example: decorating a controller method
@Controller('/content')
export class ContentController {
  @Patch()
  public async patchContent(
    @Body() body: { content: string },
  ): Promise<Content> {
    return {
      content: body.content,
    };
  }
}
Post
Sets up a route for POST requests.
Post(path?: string): MethodDecorator
Parameters
- path(optional string): Route path mounted under the controller's base path. Defaults to- '/'. Example:- @Post('/create')maps to- POST <controllerPath>/create.
Example: decorating a controller method
@Controller('/content')
export class ContentController {
  @Post()
  public async createContent(
    @Body() body: { content: string },
  ): Promise<Content> {
    return {
      content: body.content,
    };
  }
}
Put
Sets up a route for PUT requests.
Put(path?: string): MethodDecorator
Parameters
- path(optional string): Route path mounted under the controller's base path. Defaults to '/'. Example: @Put('/update') maps to PUT <controllerPath>/update.
Notes
- Use @Body to read the request payload for PUT.
Example: decorating a controller method
@Controller('/content')
export class ContentController {
  @Put()
  public async updateContent(
    @Body() body: { content: string },
  ): Promise<Content> {
    return {
      content: body.content,
    };
  }
}