{"record":{"id":"69ebf285aa15a218","repo":"nestjs/nest","slug":"cannot-apply-global-guards-registration-must-occu","errorCode":null,"errorMessage":"Cannot apply global guards: registration must occur before initialization.","messagePattern":"Cannot apply global guards: registration must occur before initialization\\.","errorType":"console","errorClass":null,"httpStatus":null,"severity":"warning","filePath":"packages/microservices/nest-microservice.ts","lineNumber":242,"sourceCode":"      );\n    }\n\n    interceptors = this.applyInstanceDecoratorIfRegistered<NestInterceptor>(\n      ...interceptors,\n    );\n    this.applicationConfig.useGlobalInterceptors(...interceptors);\n    interceptors.forEach(item =>\n      this.graphInspector.insertOrphanedEnhancer({\n        subtype: 'interceptor',\n        ref: item,\n      }),\n    );\n    return this;\n  }\n\n  public useGlobalGuards(...guards: CanActivate[]): this {\n    if (this.isInitialized) {\n      this.logger.warn(\n        'Cannot apply global guards: registration must occur before initialization.',\n      );\n    }\n\n    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   *","sourceCodeStart":224,"sourceCodeEnd":260,"githubUrl":"https://github.com/nestjs/nest/blob/3f8a0ce1832fb30053f55856088371b097bbf7e1/packages/microservices/nest-microservice.ts#L224-L260","documentation":"NestMicroservice.useGlobalGuards logs this warning when guards are registered after the microservice has initialized (isInitialized is true). Handler pipelines, including global guard chains, are frozen at init() time; the late guards are stored in the ApplicationConfig and inserted into the graph inspector as orphaned enhancers, but no already-created pattern handler will consult them. The method chain continues without error, which makes the lost authorization easy to miss.","triggerScenarios":"Calling app.useGlobalGuards(new RolesGuard()) after `await app.listen()` or `await app.init()`, e.g. because the guard depends on an auth server URL or JWKS that only resolves post-startup, or because registration was moved into a start script that runs after the listener is up.","commonSituations":"Auth guards configured from asynchronously loaded config; guards added in onApplicationBootstrap hooks that run after the microservice initialized; hybrid apps configuring the microservice instance after startAllMicroservices(). This one is security-sensitive: handlers run without the intended authorization checks.","solutions":["Move useGlobalGuards() before `await app.listen()` / `await app.init()` — the auth config must be awaited before listen, not after.","If timing cannot be controlled, attach guards per-handler with @UseGuards() so they are baked in at decoration time.","Add a startup assertion (fail fast if the guard is missing from config) plus CI log scanning for this warning, since running without the guard is a security hole.","For hybrid apps, register global guards on the main application before starting microservices."],"exampleFix":"// before\nconst app = await NestFactory.createMicroservice(AppModule, opts);\nawait app.listen();\nconst auth = await loadAuthConfig();\napp.useGlobalGuards(new AuthGuard(auth)); // warning: guard never applied\n\n// after\nconst auth = await loadAuthConfig();\nconst app = await NestFactory.createMicroservice(AppModule, opts);\napp.useGlobalGuards(new AuthGuard(auth));\nawait app.listen();","handlingStrategy":"validation","validationCode":"const auth = await loadAuthConfig(); // resolve deps first\nconst app = await NestFactory.createMicroservice(AppModule, opts);\nif ((app as any).isInitialized) {\n  throw new Error('Bootstrap order bug: guards must be registered before init/listen');\n}\napp.useGlobalGuards(new AuthGuard(auth));\nawait app.listen();","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Await auth/JWKS/config before creating the app so guards can be registered pre-init","Security-sensitive: add an integration test asserting a request without credentials is rejected, proving the guard is active","Fail CI on this warning string — a missing guard means handlers run unauthorized","Use @UseGuards() on handlers as a timing-proof alternative"],"tags":["nestjs","microservices","guards","security","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-14T00:17:10.932Z"}