01 / 12

How do you apply global middleware, pipes, guards, or interceptors in NestJS?

Difficulty: 6/10
Middleware, Interceptors, Guards

Use app.useGlobalPipes(), app.useGlobalGuards(), app.useGlobalInterceptors(), and app.useGlobalFilters(). These bypass DI so they cannot inject services. To use DI, register globals inside a module using the APP_GUARD, APP_PIPE, APP_INTERCEPTOR, or APP_FILTER tokens.

Two ways to register global enhancers
Key difference:
  1. 1

    app.useGlobal*() — simple but cannot inject services; use for dependency-free enhancers.

  2. 2

    APP_* tokens — registered inside the DI container; supports full constructor injection.

  3. 3

    The APP_* token approach is preferred for any enhancer that has dependencies.

Scenario Questions

0-2 years experience

  1. 1How would you add a global middleware in NestJS to log every incoming request URL and method?
  2. 2What happens if you register a global guard that always returns false — will any endpoint still work?

2-5 years experience

  1. 1Our global interceptor is modifying the response body, but one endpoint now returns a file stream — the file is corrupted. How do you fix this without removing the interceptor?
  2. 2A teammate added a global pipe that validates all inputs, but now our health check endpoint is failing. How do you exempt it without touching every route?

5-8 years experience

  1. 1We have 15 microservices using NestJS, each with their own global interceptors for logging and metrics — but now we’re seeing performance degradation under load. How would you diagnose and optimize this?
  2. 2How would you design a system where different teams can register their own global interceptors without conflicting, while still maintaining a consistent request/response flow?

8+ years experience

  1. 1We’re migrating from Express to NestJS and have hundreds of legacy routes with custom middleware — how would you architect a phased rollout of global interceptors and guards without breaking existing clients?
  2. 2How would you enforce cross-cutting concerns like authentication and audit logging across multiple NestJS applications owned by different teams, while allowing each team to extend or override behavior safely?

Follow-up Questions

  • What happens if you register a global guard that throws an error before the controller is reached?
  • How would you debug a global interceptor that’s not being called on a specific route?
  • Can you apply a middleware globally but exclude it for certain paths?
Share

Share via WhatsApp, X, Facebook, LinkedIn or copy link. Open Graph preview enabled.