{"record":{"id":"b072b980cc934b72","repo":"nestjs/nest","slug":"cannot-apply-global-prerequest-hooks-registration","errorCode":null,"errorMessage":"Cannot apply global preRequest hooks: registration must occur before initialization.","messagePattern":"Cannot apply global preRequest hooks: registration must occur before initialization\\.","errorType":"console","errorClass":null,"httpStatus":null,"severity":"warning","filePath":"packages/microservices/nest-microservice.ts","lineNumber":265,"sourceCode":"    guards = this.applyInstanceDecoratorIfRegistered<CanActivate>(...guards);\n    this.applicationConfig.useGlobalGuards(...guards);\n    guards.forEach(item =>\n      this.graphInspector.insertOrphanedEnhancer({\n        subtype: 'guard',\n        ref: item,\n      }),\n    );\n    return this;\n  }\n\n  /**\n   * Registers a global preRequest hook (executed before all enhancers for every pattern handler).\n   *\n   * @param {...PreRequestHook} hooks\n   */\n  public registerPreRequestHook(...hooks: PreRequestHook[]): this {\n    if (this.isInitialized) {\n      this.logger.warn(\n        'Cannot apply global preRequest hooks: registration must occur before initialization.',\n      );\n    }\n    this.applicationConfig.registerPreRequestHook(...hooks);\n    return this;\n  }\n\n  public async init(): Promise<this> {\n    if (this.isInitialized) {\n      return this;\n    }\n\n    // Lazy-load optional socket module (ESM-compatible)\n    await this.loadSocketModule();\n    await super.init();\n    await this.registerModules();\n    return this;\n  }","sourceCodeStart":247,"sourceCodeEnd":283,"githubUrl":"https://github.com/nestjs/nest/blob/3f8a0ce1832fb30053f55856088371b097bbf7e1/packages/microservices/nest-microservice.ts#L247-L283","documentation":"NestMicroservice.registerPreRequestHook logs this warning when a global preRequest hook (code meant to run before all enhancers for every pattern handler) is registered after initialization. The hook list is consumed when the microservice wires up its handlers during init(); a late registration only updates the ApplicationConfig, so the hook is never invoked for the already-built handlers. The call does not throw, so the hook silently does nothing.","triggerScenarios":"Calling app.registerPreRequestHook(hook) after `await app.listen()` or `await app.init()`, typically for tenant-context, trace-propagation, or tenant/ledger setup hooks that are wired in from async bootstrap code or a plugin that activates once the broker connection is up.","commonSituations":"Multi-tenant context or correlation-id hooks installed after startup; plugins/SDKs (observability vendors) that attach hooks lazily on first request; hybrid apps where the microservice instance is configured after startAllMicroservices() has run.","solutions":["Call registerPreRequestHook() before `await app.listen()` / `await app.init()`.","If the hook needs async data, resolve it first and only then create + configure + listen, so registration stays pre-init.","Verify with a startup smoke request that the hook actually fired (e.g. assert the trace/tenant context appears), and fail CI on this warning."],"exampleFix":"// before\nconst app = await NestFactory.createMicroservice(AppModule, opts);\nawait app.listen();\napp.registerPreRequestHook(new TenantContextHook()); // warning: hook never runs\n\n// after\nconst app = await NestFactory.createMicroservice(AppModule, opts);\napp.registerPreRequestHook(new TenantContextHook());\nawait app.listen();","handlingStrategy":"validation","validationCode":"const app = await NestFactory.createMicroservice(AppModule, opts);\nif ((app as any).isInitialized) {\n  throw new Error('Bootstrap order bug: pre-request hooks must be registered before init/listen');\n}\napp.registerPreRequestHook(new TenantContextHook());\nawait app.listen();","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Register pre-request hooks in the same bootstrap block as other global enhancers, before listen()","Resolve any async data the hook needs before app creation","Send a startup smoke request and assert the hook's side effect (trace id, tenant context) is present","Fail CI on this warning string in startup logs"],"tags":["nestjs","microservices","pre-request-hooks","lifecycle","bootstrap-order"],"backgroundTag":"global-enhancers-after-initialization","analyzedSha":"3f8a0ce1832fb30053f55856088371b097bbf7e1","analyzedAt":"2026-08-21T19:39:39.867Z","contentChangedAt":"2026-08-21T19:39:39.867Z","schemaVersion":2},"datasetVersion":"2026-09-14T05:17:10.506Z"}