← blog
NestjsNovember 21, 2026 · 15 min read

NestJS APP_FILTER Scope: Why Your Global Filter Might Not Fire

A request-scoped APP_FILTER in NestJS can silently stop catching exceptions. Learn the fix NestJS 12 shipped, plus a copy-paste cheat sheet.

Parsa Jiravand · Frontend engineer · building bestpractic
NestJS APP_FILTER Scope: Why Your Global Filter Might Not Fire

A team registers a global exception filter with APP_FILTER so every unhandled error gets the same JSON shape and the same Sentry breadcrumb. It works in every test, every staging deploy, every manual check. Then, weeks later, someone notices a slice of production 500s never reached Sentry at all — same error types, same routes, just silently missing. Nobody touched the filter. Nobody touched the module it lives in.

The filter was never a reliable singleton at all. The moment its constructor started injecting a request-scoped provider — to log the current tenant, say — Nest quietly turned the filter itself request-scoped too. And for every NestJS release before 12.1.3, a REQUEST- or TRANSIENT-scoped class registered as a global enhancer this way wasn't rejected, wasn't logged, wasn't flagged at boot — Nest built it anyway, as an empty object whose constructor had never run, and handed it real requests to handle. The dependency it needed just wasn't there. This article is about that gap, the fix NestJS 12 actually shipped for it (in two separate releases, for two different reasons), and the real-but-narrower hole in exception-filter coverage that remains today.

This is written against NestJS 12.5.0 (verified against @nestjs/core's npm dist-tags; the 11.x line is on the legacy npm tag at 11.2.10). The specific fixes this article walks through landed in 12.1.3 and 12.2.0 — both are included in 12.5.0 — and everything described is core-container behavior, so it is identical whether your HttpAdapter is Express or Fastify.

By the end of this article you'll be able to:

  • Explain exactly how a provider's injection scope can propagate into a global guard, interceptor, pipe, or filter without you ever writing scope: on it
  • Name the real difference between app.useGlobalFilters() and the APP_FILTER provider token, and why only one of them can inject dependencies at all
  • State precisely what changed in NestJS 12.1.3 and 12.2.0, and why filters now get different treatment than guards and interceptors
  • Recognize the one combination that still silently loses coverage today, even on a current NestJS install
  • Design a global exception filter that stays reliably global, on purpose

You've written a custom exception filter and registered it with APP_FILTER from @nestjs/core. You don't need prior experience with Nest's injection scopes — this article builds that model from the ground up.

Here's the filter, trimmed to the part that matters:

TypeScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// all-exceptions.filter.ts @Catch() @Injectable() export class AllExceptionsFilter implements ExceptionFilter { constructor(private readonly tenantContext: TenantContextService) {} catch(exception: unknown, host: ArgumentsHost) { const ctx = host.switchToHttp(); const response = ctx.getResponse(); // tenantContext reads the current request's tenant for the error report reportToSentry(exception, this.tenantContext.tenantId); response.status(500).json({ message: 'Internal server error' }); } }
TypeScript
1
2
3
4
5
6
7
8
// tenant-context.service.ts @Injectable({ scope: Scope.REQUEST }) export class TenantContextService { constructor(@Inject(REQUEST) private readonly request: Request) {} get tenantId() { return this.request.headers['x-tenant-id']; } }
TypeScript
1
2
3
4
5
6
7
8
// app.module.ts @Module({ providers: [ TenantContextService, { provide: APP_FILTER, useClass: AllExceptionsFilter }, ], }) export class AppModule {}

Nothing here looks wrong. AllExceptionsFilter is registered with APP_FILTER, which the docs describe as making a filter global "regardless of the module in which this construction is employed." It never calls scope: Scope.REQUEST on itself — only TenantContextService does that, so it can read the inbound request. But TenantContextService is REQUEST-scoped, and injecting a REQUEST-scoped provider into another provider's constructor makes that provider REQUEST-scoped too. That's not a bug — it's how Nest's injection scope has always worked. It just means AllExceptionsFilter is REQUEST-scoped now, whether or not anyone intended it.

On every NestJS release before 12.1.3, that combination — a REQUEST- or TRANSIENT-scoped class registered as a global enhancer via useClass — booted cleanly, with no startup error and no warning. But it wasn't a quiet skip: Nest still constructed AllExceptionsFilter, as a bare instance whose constructor body never ran, and still called catch() on that instance for every matching exception. this.tenantContext was undefined inside that method, so the filter's own body threw the moment it tried to read tenantId — no Sentry call went out, because the code never got that far, but it also wasn't a clean, silent handoff to Nest's default handler the way it might look from the outside. (nestjs/nest PR #18104 describes the identical mechanism for a useClass global guard, whose canActivate would "run with its dependency undefined, causing a 500 on every request.")

The mental model: a guard, interceptor, pipe, or filter is a provider like any other, which means it follows the exact same scope-propagation rule every other provider does: if its constructor injects a REQUEST-scoped (or TRANSIENT-scoped) dependency, the enhancer itself inherits that scope — even though you only wrote scope: on the dependency, never on the enhancer. Scope bubbles up through constructor injection; it doesn't stay contained to the provider you explicitly marked.

That rule is reasonable and documented for ordinary services. What it does not come with, anywhere in NestJS's own docs, is a warning that applying it to a global enhancer changes what "global" means. APP_FILTER's own documentation says it makes a filter global "regardless of the module" — true, but silent on scope. The two ideas collide exactly where this bug lives: a provider-level rule (scope bubbling) meets a global-registration guarantee (APP_FILTER), and the guarantee quietly loses.

Key concept: "global" and "singleton" are two different promises. APP_FILTER promises your filter is wired into every route. Scope decides whether Nest can actually keep one instance of it alive for the whole app to share — and if it can't, the global promise is the one that breaks, not the scope.

Runs right in your browser — poke at it and watch the concept react live.

NestJS gives you two ways to make a filter apply everywhere, and they are not interchangeable:

TypeScript
1
2
3
4
// main.ts — instance-based, works but can't use DI const app = await NestFactory.create(AppModule); app.useGlobalFilters(new AllExceptionsFilter()); await app.listen(3000);
TypeScript
1
2
3
4
5
// app.module.ts — provider-based, can use DI @Module({ providers: [{ provide: APP_FILTER, useClass: AllExceptionsFilter }], }) export class AppModule {}

app.useGlobalFilters() instantiates the filter yourself, outside of any module — which means it cannot inject anything, because injection only happens inside Nest's module context. APP_FILTER solves exactly that: register the filter as a provider inside any module, and Nest constructs it through the DI container like anything else, dependencies included. That's the whole reason APP_FILTER exists. It's also exactly the door this bug walks through — DI means scope, and scope is where things went wrong above.

The dangerous part of this bug isn't that someone deliberately wrote @Injectable({ scope: Scope.REQUEST }) on a global filter — that would at least be a visible decision to review. It's that scope arrives as a side effect of an unrelated choice three steps away:

  • You need the current user, tenant, or request ID inside your filter.
  • The idiomatic way to get it is a small REQUEST-scoped service that wraps @Inject(REQUEST).
  • You inject that service into your filter's constructor.
  • Nest's scope-bubbling rule — the same one that makes a controller request-scoped when it depends on a request-scoped service — makes your filter request-scoped too, silently.

Nobody on the team ever typed scope: on AllExceptionsFilter. The filter's own file never changed. The regression shipped the day TenantContextService was added as a dependency — which, if no commit touched all-exceptions.filter.ts, made it look like the opposite of the filter's job was the cause.

The 12.1.3 release shipped two separate fixes for this, back to back:

  • "fix(core): stop silently dropping request-scoped global enhancers" — fixed the other half of this family of bugs: a scoped global enhancer registered via useExisting or useFactory (not the useClass style this article uses) really was filtered out and skipped entirely, because Nest's old check looked for a null instance — something a class provider never has. After this fix, Nest tries to actually use the enhancer instead of discarding it.
  • "fix(core): fail at startup for request-scoped class global enhancers" — the fix for AllExceptionsFilter's actual registration style, useClass. Before this landed, a scoped class enhancer wasn't dropped at all: Nest built it as a broken, constructor-never-ran instance and called it anyway on real requests. After this, Nest refuses to boot the app instead — an explicit startup error, before a single request can be served.

Read together, these two PRs replace "silently does nothing" with "crashes loudly instead." That's a strict improvement for safety — a guard that silently vanishes could mean an unprotected route in production; an app that won't start at all gets caught in CI, by a human, before it ships. But it's also a blunt instrument: it treats every scoped global enhancer as an error, full stop, with no room for "this one still mostly works."

A separate fix in the same release — "fix(core,microservices): run transient global enhancers on controllers" — addressed the TRANSIENT-scope side of the same family of bugs, making transient global enhancers actually apply at the controller level instead of being skipped there too.

Then 12.2.0 carved out an exception for exception filters. Under its "new defaults and behaviour changes," the release notes say a request- or transient-scoped APP_FILTER "now logs a startup warning, as it only applies to exceptions thrown from controllers" — a warning, not the startup failure that 12.1.3 introduced for other scoped global enhancers.

That's a meaningful change in posture. A scoped global guard that sometimes doesn't run is a security hole, not a guard — failing to boot is the right call there. A scoped global filter is different: it can still genuinely catch and format exceptions thrown inside a normal controller request, the overwhelming majority of what filters exist for. So current NestJS boots your app, logs one explicit warning naming the limitation, and lets the filter do the part of its job it still can.

The same release tightened one more related behavior: "a global enhancer that the injector failed to instantiate now fails the application at startup" — not filter-specific, but it closes a related class of silent-failure bugs at the DI level.

Here's the part worth sitting with: the 12.2.0 warning doesn't say your scoped filter is fine now. It says, in its own words, that it "only applies to exceptions thrown from controllers." The docs are explicit that exceptions thrown from middleware bypass method- and controller-level @UseFilters() entirely and reach only a truly global filter, because middleware runs before any route (and its handler-level filters) has even been selected.

Put those two facts together: on current NestJS, a REQUEST- or TRANSIENT-scoped APP_FILTER still does not catch an exception thrown from middleware. It boots. It logs a warning. It catches everything a developer is most likely to test by hand — a thrown error inside a controller method. The one case it silently drops is the one almost nobody manually tests: an exception from a piece of middleware that runs before the controller is even picked. That's the honest shape of "fixed" here — loud and correct for the common path, still a quiet gap for the uncommon one, and now at least documented in a boot-time log line instead of nowhere at all.

Instant feedback, a hint on every question, and an explanation for each answer — right or wrong.

  • The REQUEST token itself forces scope, full stop. Injecting REQUEST or CONTEXT (GraphQL) directly makes the injecting provider request-scoped regardless of any scope: you declare.
  • TRANSIENT doesn't normally bubble, but global registration is the exception. An ordinary provider that injects a TRANSIENT dependency gets its own private copy without becoming transient itself. Global enhancers go through separate instantiation logic, which is why they needed their own dedicated fix (PR #17993).
  • A test suite usually can't catch this. Test.createTestingModule({...}).compile() typically never exercises the startup path 12.1.3's "fail fast" check runs against, so a unit test can pass green while a real NestFactory.create() boot would refuse to start.
  • app.useGlobalFilters() never has this problem, by construction. No DI, so no scope to bubble — at the cost of never being able to inject anything either.
  • Durable providers don't rescue this. durable: true changes how a REQUEST-scoped provider is reused; it doesn't turn it back into a true singleton.

  • Read the current user/tenant/request ID without scoping your filter at all. Reach for AsyncLocalStorage, populated once in a small piece of middleware, instead of injecting a REQUEST-scoped service into a global filter. The filter stays a true singleton and still gets per-request context.
  • If a global enhancer truly must be request-scoped, know what you're giving up. For a filter, that's middleware-thrown exceptions. For a guard, interceptor, or pipe, current NestJS won't let the app start at all.
  • Never assume a scoped global enhancer "mostly works" without checking the version. Silently broken (undefined dependencies at runtime), startup failure, or startup warning with reduced coverage — it depends on which NestJS version you're running, and it changed twice in the 12.x line alone.
  • Treat the 12.2.0 startup warning as a real signal, not log noise. It names the exact gap above, not a vague best-practice nudge.
  • Re-read a point release's notes before assuming "patch, no risk." 12.1.3 and 12.2.0 are both patch versions under semver, and both changed real runtime behavior here.

No. app.useGlobalFilters() instantiates the filter yourself, outside any module's DI context, so it can't inject dependencies at all — and with no injection, there's nothing to bubble scope from. The tradeoff is that you lose dependency injection entirely, which is the exact capability APP_FILTER exists to provide.

Not on 12.1.3 or later. The startup-failure fix in that release applies to request-scoped class global enhancers generally — guards, interceptors, and pipes included — so the broken-instance case for those is closed; you get a boot-time error instead of a provider with an undefined dependency.

NestJS's own 12.2.0 release notes don't spell out the reasoning, only the behavior: a scoped APP_FILTER "logs a startup warning, as it only applies to exceptions thrown from controllers." In practice, a scope-limited filter can still correctly handle the overwhelming majority of exceptions — anything thrown during normal request handling — while a scope-limited guard protecting nothing would be a straightforward security gap. Treat the warning as "mostly still correct, with one named gap," not as "fine."

No. Scope resolution and global-enhancer instantiation happen in Nest's core container, before either HttpAdapter is involved, so the behavior described here is identical on both.

Compare your installed @nestjs/core version against 12.1.3 and 12.2.0 — npm ls @nestjs/core locally, or npm view @nestjs/core dist-tags for what's current. Below 12.1.3, you have the broken-instance bug — the filter boots and runs, but its injected dependency is undefined. At 12.1.3 up to (not including) 12.2.0, a scoped class filter fails your app at boot. At 12.2.0 and later, it boots with a warning and the middleware-exception gap described in Stage 5.

SituationNestJS < 12.1.3NestJS 12.1.3NestJS 12.2.0+ (current)
Scoped (REQUEST/TRANSIENT) class filter via APP_FILTERBoots with no warning, but built as a broken constructor-never-ran instance — throws when it touches its own missing dependencyApp fails to startBoots, logs a startup warning, catches controller exceptions only
Scoped class guard/interceptor/pipe, globally registeredBoots with no warning, same broken-instance problem — undefined dependencies at runtimeApp fails to startApp fails to start (unchanged from 12.1.3)
Singleton (default-scope) global filter via APP_FILTERFully global: catches middleware + controller exceptionsSameSame
app.useGlobalFilters() filterAlways global, never scoped (can't inject deps)SameSame
Read current user/tenant in a global filter safely——AsyncLocalStorage, not an injected REQUEST-scoped provider
Check your exposure——npm view @nestjs/core dist-tags and compare against 12.1.3 / 12.2.0

  • Scope bubbles through constructor injection, and that rule doesn't stop at the edge of a global enhancer — a filter, guard, interceptor, or pipe inherits REQUEST/TRANSIENT scope from any dependency it injects, even if no one wrote scope: on the enhancer itself.
  • Before NestJS 12.1.3, that combination wasn't dropped at startup — it booted silently, then broke the first time it ran: no error, no warning, just a constructor that never executed and a dependency that was undefined when the filter tried to use it.
  • 12.1.3 replaced the silent drop with a startup failure for scoped class global enhancers. 12.2.0 then gave exception filters specifically a softer path: boot with a warning, keep working for controller exceptions, and openly admit the one thing it still can't do — catch exceptions thrown from middleware.
  • The fix that avoids all three outcomes is the same fix in every case: keep the global enhancer a singleton, and reach for AsyncLocalStorage when it needs per-request context.

The team in this article's opening didn't lose Sentry coverage the day they upgraded NestJS, and they didn't lose it the day they wrote the filter either — they lost it the day TenantContextService became one of its dependencies, three steps removed from anything that looked like a scope decision. Once "global" and "singleton" are two separate promises in your head, that bug stops being something you discover in production and becomes something you can rule out by reading a constructor.

Has a dependency you added somewhere else ever quietly changed the scope of something you thought was a fixed singleton? Drop it in the comments.


🚀 Want more like this? Every guide, playground, and quiz lives on bestpractic.org — open it and sign up free so the next one finds you.

Thanks for reading! Let's stay connected:

Keep reading

One post a day, in your inbox

Each one with a runnable playground and a quiz. No pitch, no digest, unsubscribe in one click.

0 comments

Sign in to join the discussion, like comments, and save articles for later.