nestjs/nest · warning

Cannot apply global guards: registration must occur before i

Error message

Cannot apply global guards: registration must occur before initialization.

What it means

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.

Source

Thrown at packages/microservices/nest-microservice.ts:242

      );
    }

    interceptors = this.applyInstanceDecoratorIfRegistered<NestInterceptor>(
      ...interceptors,
    );
    this.applicationConfig.useGlobalInterceptors(...interceptors);
    interceptors.forEach(item =>
      this.graphInspector.insertOrphanedEnhancer({
        subtype: 'interceptor',
        ref: item,
      }),
    );
    return this;
  }

  public useGlobalGuards(...guards: CanActivate[]): this {
    if (this.isInitialized) {
      this.logger.warn(
        'Cannot apply global guards: registration must occur before initialization.',
      );
    }

    guards = this.applyInstanceDecoratorIfRegistered<CanActivate>(...guards);
    this.applicationConfig.useGlobalGuards(...guards);
    guards.forEach(item =>
      this.graphInspector.insertOrphanedEnhancer({
        subtype: 'guard',
        ref: item,
      }),
    );
    return this;
  }

  /**
   * Registers a global preRequest hook (executed before all enhancers for every pattern handler).
   *

View on GitHub (pinned to 3f8a0ce183)

Solutions

  1. Move useGlobalGuards() before `await app.listen()` / `await app.init()` — the auth config must be awaited before listen, not after.
  2. If timing cannot be controlled, attach guards per-handler with @UseGuards() so they are baked in at decoration time.
  3. 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.
  4. For hybrid apps, register global guards on the main application before starting microservices.

Example fix

// before
const app = await NestFactory.createMicroservice(AppModule, opts);
await app.listen();
const auth = await loadAuthConfig();
app.useGlobalGuards(new AuthGuard(auth)); // warning: guard never applied

// after
const auth = await loadAuthConfig();
const app = await NestFactory.createMicroservice(AppModule, opts);
app.useGlobalGuards(new AuthGuard(auth));
await app.listen();
Defensive patterns

Strategy: validation

Validate before calling

const auth = await loadAuthConfig(); // resolve deps first
const app = await NestFactory.createMicroservice(AppModule, opts);
if ((app as any).isInitialized) {
  throw new Error('Bootstrap order bug: guards must be registered before init/listen');
}
app.useGlobalGuards(new AuthGuard(auth));
await app.listen();

Prevention

When it happens

Trigger: 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.

Common situations: 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.

Related errors


AI-assisted analysis of nestjs/nest@3f8a0ce183 (2026-08-21). Data as JSON: /api/errors/69ebf285aa15a218. Report an issue: GitHub.