@Middleware() is similar to the Express middleware with the difference that it's a class and you can use the IoC to inject other services on his constructor.

All middlewares decorated by @Middleware or @MiddlewareError have one method named use(). This method can use all parameters decorators as you could see with the Controllers and return promise.


To begin, you must adding the middlewares folder on componentsScan attribute in your server settings as follow :

import {ServerLoader} from "@tsed/common";
import Path = require("path");
const rootDir = Path.resolve(__dirname);

   mount: {
      '/rest': `${rootDir}/controllers/**/**.js`
   componentsScan: [
export class Server extends ServerLoader {


Then, create a new file in your middlewares folder. Create a new Class definition then add the @Middleware() or @MiddlewareError() annotations on your class.

You have different use cases to declare and use a middleware. Theses use cases are following:

Specifics parameters decorators

In addition, you have this specifics parameters decorators for the middlewares:

Signature Example Description
@Err() useMethod(@Err() err: any) {} Inject the Express.Err service. (Decorator for middleware).
@ResponseData() useMethod(@ResponseData() data: any) Provide the data returned by the previous middlewares.
@EndpointInfo() useMethod(@EndpointInfo() endpoint: Endpoint) Provide the endpoint settings.

Override existing middlewares

The decorator @OverrideMiddleware gives you the ability to override some internal Ts.ED middlewares like:

All middlewares provided by Ts.ED can be overridden. You can find the complete list here.


import {OriginalMiddlware, OverrideMiddleware} from "@tsed/common";

export class CustomMiddleware extends OriginalMiddlware {
    public use() {


By default, the server import automatically you middlewares matching with this rules ${rootDir}/middlewares/**/*.ts (See componentScan configuration).

├── src
│   ├── controllers
│   ├── services
│   ├── middlewares
│   └── Server.ts
└── package.json

If not, just import your middleware in your server or edit the componentScan configuration.

import {ServerLoader, ServerSettings} from "@tsed/common";
import "./src/other/directory/CustomMiddleware";

export class Server extends ServerLoader {