{"record":{"id":"9a00bfbe01461065","repo":"nestjs/nest","slug":"the-middleware-doesn-t-provide-the-use-method","errorCode":null,"errorMessage":"The middleware doesn't provide the 'use' method (${name})","messagePattern":"The middleware doesn't provide the 'use' method \\((.+?)\\)","errorType":"exception","errorClass":"InvalidMiddlewareException","httpStatus":null,"severity":"critical","filePath":"packages/core/middleware/middleware-module.ts","lineNumber":254,"sourceCode":"        applicationRef,\n        routeInfo,\n        moduleRef,\n        collection,\n      );\n    }\n  }\n\n  private async bindHandler(\n    wrapper: InstanceWrapper<NestMiddleware>,\n    applicationRef: HttpServer,\n    routeInfo: RouteInfo,\n    moduleRef: Module,\n    collection: Map<InjectionToken, InstanceWrapper>,\n  ) {\n    const { instance, metatype } = wrapper;\n\n    if (isUndefined(instance?.use)) {\n      throw new InvalidMiddlewareException(metatype!.name);\n    }\n    const isStatic = wrapper.isDependencyTreeStatic();\n    if (isStatic) {\n      const proxy = await this.createProxy(instance);\n      return this.registerHandler(applicationRef, routeInfo, proxy);\n    }\n\n    const isTreeDurable = wrapper.isDependencyTreeDurable();\n\n    await this.registerHandler(\n      applicationRef,\n      routeInfo,\n      async <TRequest, TResponse>(\n        req: TRequest,\n        res: TResponse,\n        next: () => void,\n      ) => {\n        try {","sourceCodeStart":236,"sourceCodeEnd":272,"githubUrl":"https://github.com/nestjs/nest/blob/dd75d7bd8c5e88048587e6768d36eb695f3e7a25/packages/core/middleware/middleware-module.ts#L236-L272","documentation":"Middleware in NestJS must implement the NestMiddleware contract — an instance method `use(req, res, next)`. During middleware registration the framework checks `instance.use`; when it is undefined, InvalidMiddlewareException ('The middleware doesn't provide the use method (X)') stops bootstrap because the middleware could never handle a request.","triggerScenarios":"A class listed in `module.configure(consumer)` via `consumer.apply(X).forRoutes(...)` has no `use` method; `use` was renamed (handle/run), made static, arrow-bound as a class field on a subclass that lost it, or defined on an interface never implemented; applying a plain function or object instead of a class; TypeScript weakening the class to `any` so the missing method compiles.","commonSituations":"Porting Express middleware objects into NestJS without wrapping them in a class; renaming use() to match custom conventions; middleware split into base + derived class where the base declares `use` abstract but the derived forgets it; class-based middleware written by developers used to function middleware.","solutions":["Implement the interface: `export class LoggerMiddleware implements NestMiddleware { use(req: Request, res: Response, next: NextFunction) { ... } }`.","Check for typos/renames and make sure `use` is a regular instance method (not static, not a getter).","For existing Express-style functions, adapt them: `use(req, res, next) { expressFn(req, res, next); }` or use `consumer.apply(wrap(expressFn))` patterns.","Add `implements NestMiddleware` so the compiler enforces the method before runtime."],"exampleFix":"// before\nexport class AuthMiddleware { // no use()\n  handle(req: any, res: any, next: () => void) { next(); }\n}\n\n// after\nimport { NestMiddleware } from '@nestjs/common';\n\nexport class AuthMiddleware implements NestMiddleware {\n  use(req: Request, res: Response, next: NextFunction) {\n    // ...\n    next();\n  }\n}","handlingStrategy":"type-guard","validationCode":"// Fail fast if a middleware class lacks use() before it reaches the framework\ninterface MiddlewareLike { use(...args: any[]): any }\n\nconst implementsUse = (cls: Function): cls is new () => MiddlewareLike =>\n  typeof (cls.prototype as any)?.use === 'function';\n\n// in the module's configure():\nif (!implementsUse(AuthMiddleware)) {\n  throw new Error('AuthMiddleware must implement NestMiddleware (use method)');\n}\nconsumer.apply(AuthMiddleware).forRoutes('*');","typeGuard":"const isNestMiddleware = (v: any): v is import('@nestjs/common').NestMiddleware =>\n  !!v && typeof v.use === 'function';","tryCatchPattern":null,"preventionTips":["Always write `implements NestMiddleware` on middleware classes so the compiler enforces use().","Add a wiring test that iterates middleware classes and asserts typeof cls.prototype.use === 'function'.","Wrap legacy Express functions in a class adapter instead of passing them to consumer.apply()."],"tags":["middleware","contract","http","bootstrap"],"backgroundTag":"middleware-invalid-implementation","analyzedSha":"dd75d7bd8c5e88048587e6768d36eb695f3e7a25","analyzedAt":"2026-08-21T19:39:39.867Z","contentChangedAt":"2026-08-21T19:39:39.867Z","schemaVersion":2},"datasetVersion":"2026-09-14T05:17:10.506Z"}