User 42 fetches GET /documents/7, the document they own. The response includes isOwner: true. A minute later, user 7 — who has read access but doesn't own it — fetches the exact same document. The response also says isOwner: true. User 7 now sees an "Edit" button a permission check downstream will eventually reject, but the UI already lied to them, and a client that trusts isOwner to gate a destructive action has a real authorization bug, not a cosmetic one.
Nobody touched the authorization logic. Nobody touched the DTO. Both interceptors involved are individually correct, straight from patterns NestJS's own documentation shows. The bug is entirely in the order two @UseInterceptors() arguments were listed — and until you know what that list actually builds, the order looks arbitrary.
What you'll learn
By the end of this article you'll be able to:
- Explain what
intercept(context, next)andCallHandler.handle()actually do to a request, not just that you're supposed to call them - Predict the exact execution order when interceptors are stacked at the global, controller, and method level
- Recognize why an interceptor that skips
next.handle()(like a cache) silently skips every interceptor nested inside it too - Fix a stale-personalization bug caused by interceptor order, instead of chasing it through the DTO and the authorization layer
- Choose between method-level
@UseInterceptors(),app.useGlobalInterceptors(), and theAPP_INTERCEPTORprovider token
Who this is for
You've written at least one NestJS controller with @UseGuards() or @UseInterceptors() on it, even if you copied the interceptor from the docs without fully tracing what it does. You don't need prior RxJS experience — the handful of operators used here (tap, map, catchError, of) are explained as they appear.
This article is written against NestJS 12.x (@nestjs/core is at 12.6.0 on npm latest, with 11.2.11 the last legacy-tagged 11.x release). The interceptor API — NestInterceptor, CallHandler, ExecutionContext — and the global → controller → route composition order are core-container behavior, unchanged in shape since well before v12.
Table of contents
- The problem: a cache that leaks the wrong user's permissions
- The mental model: interceptors are nested, not listed
- Stage 1: what
next.handle()actually is - Stage 2: composing two interceptors by hand
- Stage 3: the cache-and-personalization bug, reproduced
- Stage 4: global, controller, and method — the fixed nesting
- Stage 5: binding without breaking DI
- Edge cases and gotchas
- Best practices
- FAQ
- Cheat sheet
- Key takeaways
The problem: a cache that leaks the wrong user's permissions
Here's the setup that produced the bug above. Two interceptors, each individually correct and each a straightforward extension of a pattern NestJS's own documentation shows:
// Adds a per-request field: does the CURRENT caller own this document?
@Injectable()
export class OwnershipInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
const { user } = context.switchToHttp().getRequest();
return next.handle().pipe(
map((doc) => ({ ...doc, isOwner: doc.ownerId === user.id })),
);
}
}
// Caches the raw document by id — the document itself is the same for
// every viewer, so it's cached once, regardless of who's asking.
@Injectable()
export class CacheInterceptor implements NestInterceptor {
constructor(private cache: CacheStore) {}
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
const key = context.switchToHttp().getRequest().params.id;
const cached = this.cache.get(key);
if (cached) return of(cached);
return next.handle().pipe(tap((doc) => this.cache.set(key, doc)));
}
}
Both are individually reasonable: caching a shared resource by its id is a normal optimization, and stamping a per-caller isOwner flag onto a response is a normal personalization. Bound on the controller like this, reading top to bottom as "first cache, then personalize":
@UseInterceptors(CacheInterceptor, OwnershipInterceptor)
@Get(':id')
findOne(@Param('id') id: string) {
return this.documents.findOne(id);
}
User 42 (the owner) requests document 7, a cache miss: CacheInterceptor calls next.handle(), which runs OwnershipInterceptor, which runs the handler, gets back { id: 7, ownerId: 42 }, and stamps isOwner: true because the current request's user is 42. CacheInterceptor's tap() then caches that already-personalized object — { id: 7, ownerId: 42, isOwner: true } — keyed only by the document id.
User 7 (not the owner) requests the same document 7 next: CacheInterceptor finds a cached entry for key 7 and returns of(cached) directly — it never calls next.handle(), so OwnershipInterceptor never runs for this request. The response sent to user 7 is the exact object cached from user 42's request: isOwner: true. User 7 is told they own a document they don't, because the only code that could have corrected the flag for the new caller never ran.
The mental model: interceptors are nested, not listed
The mental model: @UseInterceptors(A, B) does not run A then B as two independent steps. It builds A wrapping B wrapping the handler — one nested call, not a flat list. The first interceptor you name becomes the outermost layer; the last one you name sits closest to the handler.
This matters because next.handle() is not "move to the next item in a list." It is "invoke everything nested inside me, and give me back its result as an Observable." When A calls next.handle(), that call is B's entire intercept() execution, including whatever B does before and after its own next.handle(). If A never calls next.handle() — because it short-circuits, exactly like CacheInterceptor does on a hit — then B never runs. Not "runs with stale data." Does not run, at all, on that request.
This is the same onion composition Express and Koa middleware use, and it is also how NestJS composes guards, interceptors, and pipes across scopes (confirmed by the framework's own request-lifecycle documentation): code that runs before the nested call executes in registration order, outermost first; code that runs after — the RxJS operators chained onto the Observable that next.handle() returns — unwinds in the reverse order, innermost first. Draw it as concentric rings, not a pipeline of boxes, and the cache bug above stops being surprising: CacheInterceptor is the outer ring, so skipping its next.handle() cuts out everything inside that ring, OwnershipInterceptor included.
Stage 1: what next.handle() actually is
Every NestInterceptor implements one method:
interface NestInterceptor<T = any, R = any> {
intercept(context: ExecutionContext, next: CallHandler<T>): Observable<R>;
}
context: ExecutionContext is the same object a guard sees — it carries the request, the controller class, and the handler reference. next: CallHandler has exactly one method, handle(), which invokes the rest of the chain (the next interceptor, or the route handler if there is none left) and returns an Observable of its eventual result.
Key concept: code written before return next.handle()... runs before the handler. Code chained onto the Observable that next.handle() returns — via RxJS operators like tap, map, or catchError — runs after the handler resolves, and can transform, log, or replace its result. If an interceptor never calls next.handle() and never returns an equivalent Observable, the request hangs forever: no response is ever emitted, because nothing inside Nest's response pipeline was asked to produce one.
@Injectable()
export class LoggingInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
const start = Date.now();
return next.handle().pipe(
tap(() => console.log(`${context.getHandler().name} took ${Date.now() - start}ms`)),
);
}
}
This is the minimal correct shape: do setup, call next.handle(), pipe a side effect onto the result, return it unchanged. Nothing here reorders anything else — it's a single ring with nothing nested complicated inside it.
Stage 2: composing two interceptors by hand
To see the nesting directly, strip away the decorator and write what @UseInterceptors(A, B) effectively builds for a single request:
function runStack(interceptors: NestInterceptor[], handler: () => Observable<any>, context: ExecutionContext) {
const terminal: CallHandler = { handle: handler };
// Build from the LAST interceptor outward, so the FIRST interceptor ends up outermost.
const chain = interceptors.reduceRight<CallHandler>(
(next, interceptor) => ({ handle: () => interceptor.intercept(context, next) }),
terminal,
);
return chain.handle();
}
reduceRight walks the array back-to-front, so the last interceptor in the array is wrapped first (innermost), and each one before it wraps the previous result — leaving the first interceptor in the array as the outermost CallHandler.handle() that actually gets invoked. That's a simplified model of the mechanism behind "first named, outermost" — Nest's own implementation builds the same nesting through lazy, forward recursion rather than reduceRight, but the resulting order is identical: first interceptor outermost, applied once per scope level.
Stage 3: the cache-and-personalization bug, reproduced
Swap the order from the problem section, and the leak closes, because now OwnershipInterceptor is outermost and CacheInterceptor is innermost:
@UseInterceptors(OwnershipInterceptor, CacheInterceptor)
@Get(':id')
findOne(@Param('id') id: string) {
return this.documents.findOne(id);
}
Walk the same two requests through this order. User 42, cache miss: OwnershipInterceptor (outer) calls next.handle(), which reaches CacheInterceptor (inner), which misses, calls the handler, gets { id: 7, ownerId: 42 }, and caches that raw object — no isOwner field at all, because personalization hasn't happened yet at this ring. The raw object flows back out to OwnershipInterceptor, which stamps isOwner: true for user 42. Response: { id: 7, ownerId: 42, isOwner: true }.
User 7, same document: OwnershipInterceptor (outer) still calls next.handle() — it has no reason not to, and nothing outside it short-circuited. CacheInterceptor (inner) finds a hit and returns the cached raw object without running the handler again. That raw object flows back out to OwnershipInterceptor, which — because it is never skipped when it's the outer ring — stamps a fresh isOwner field for this request's user: 7 === 42 is false. Response: { id: 7, ownerId: 42, isOwner: false }. Correct, every time, for every caller, regardless of which request happened to populate the cache.
Key concept: a ring that must re-evaluate something per request — who's asking, what they're allowed to see — has to sit outside anything that can short-circuit, never inside it. CacheInterceptor's short-circuit only ever skips what's nested inside CacheInterceptor; it can never skip a ring wrapped around it.
Stage 4: global, controller, and method — the fixed nesting
The same onion extends across scopes, and you cannot reorder it locally. For a single inbound request, Nest's own request-lifecycle documentation puts interceptors in this order going in, and the exact reverse coming back out:
-
Global interceptors (bound via
APP_INTERCEPTORorapp.useGlobalInterceptors()) — outermost. -
Controller-level interceptors (
@UseInterceptors()on the class). -
Method-level interceptors (
@UseInterceptors()on the route handler) — innermost, closest to the actual handler.
On the way back out, it's the reverse: method-level interceptors' post-handler logic runs first, then controller-level, then global last. A method-level CacheInterceptor can never be made to wrap a global LoggingInterceptor, no matter which order you list decorators in — global is always the outer ring. If you need a cache to be able to skip a cross-cutting concern like the global logger, the logger has to not depend on seeing every response in the first place, or the cache has to move to a scope at or above it.
Stage 5: binding without breaking DI
Three ways to attach an interceptor, each with a different relationship to Nest's DI container:
// Method or controller scope — Nest constructs it through DI
@UseInterceptors(CacheInterceptor)
// Global, but constructed by hand — no constructor injection works here
app.useGlobalInterceptors(new LoggingInterceptor());
// Global, constructed through DI — constructor injection, module scope, and
// test overrides via overrideProvider() all keep working
providers: [{ provide: APP_INTERCEPTOR, useClass: CacheInterceptor }]
CacheInterceptor above takes a CacheStore in its constructor. app.useGlobalInterceptors(new CacheInterceptor(???)) has no way to provide that dependency — you're back to constructing it by hand outside the container, the same trap app.useGlobalGuards() sets for a guard that needs a service injected. APP_INTERCEPTOR fixes it the same way APP_GUARD does: register it as a provider, let Nest instantiate it through DI, and it becomes global while still receiving its dependencies — and while still being swappable in tests with Test.createTestingModule().overrideProvider(CacheStore).
Edge cases and gotchas
-
An interceptor that never calls
next.handle()still has to return something RxJS can treat as a stream. Return a bare value, or nothing at all, and Nest throws immediately — aTypeErrorlike "You provided 'undefined' where a stream was expected" — which lands in your exception filters. It doesn't hang; there's no silent stall to debug. If you're building a caching or short-circuiting interceptor, always return anObservableexplicitly —of(value)is the simplest correct shape. -
A synchronous throw inside
intercept()doesn't just skip straight past every interceptor wrapped around it. Nest invokes each interceptor inside atry/catchand forwards a synchronous throw via the subscriber'serror()callback on theObservablethat invocation built — which is exactly theObservablean outer interceptor'snext.handle()returned. So even a throw that happens before this interceptor's ownnext.handle()call surfaces as a stream error there, and that outer interceptor'scatchError()can and does see it. The error only lands directly in Nest's exception filters, the same as a guard or pipe error, when nothing further out is there to catch it (the throw happens in the outermost interceptor, or no outer interceptor pipes acatchError). -
Multiple method-level interceptors still nest in the order you list them, exactly like the global/controller/method scopes do —
@UseInterceptors(A, B, C)makesAoutermost andCinnermost, all at the same method scope. -
async intercept()works fine, even though it technically returns aPromiseinstead of anObservable. Nest resolves thatPromisebefore treating the result as a stream, soasync intercept(context, next) { await doSomething(); return next.handle().pipe(map(...)); }behaves correctly — you don't needfrom()just to useawaitinside an interceptor. -
Unsubscribing from a timeout doesn't cancel work the handler already started. A
timeout(5000)operator makes Nest stop waiting, but if the handler kicked off a database write before the timeout fired, that write still runs to completion in the background.
Best practices
- Order by scope first, list order second. Decide which cross-cutting concerns (logging, auth context, response envelope) must see every response regardless of what a more specific interceptor does, and put those at the outer scope — global over controller over method — rather than trying to win with list order inside one scope.
- Short-circuiting interceptors (cache, dedupe) belong as far inward as the response contract allows, nested inside anything that must re-evaluate per caller — authorization flags, user-specific fields, anything derived from "who is asking."
-
Prefer
APP_INTERCEPTORoverapp.useGlobalInterceptors()the moment an interceptor has a constructor dependency. It costs nothing and keeps the interceptor testable. - Keep one interceptor doing one thing. A single interceptor that logs, caches, and transforms is unreadable to reorder safely later — the stacking bug above is much easier to spot in review when each interceptor is a named, single-purpose ring.
- When a bug looks like "sometimes the response has stale or wrong per-user data," suspect interceptor ordering before suspecting the data layer. A field that's correct for one caller and wrong for the next, correlated with a cache hit, is a strong signal to check which interceptor is nested inside which.
FAQ
Does interceptor order matter if neither one short-circuits?
Less, but not never. If both interceptors always call next.handle() and only add side effects or transforms, the pre-handler logic still runs outer-to-inner and the post-handler logic still runs inner-to-outer — so a tap() that logs "before" timing in one interceptor and a map() that reshapes data in another can still produce a different final object depending on which one is outermost, even though both always run.
Can I make a method-level interceptor run before a global one?
No. The scope ordering (global, then controller, then method) is fixed by Nest's request pipeline and isn't something @UseInterceptors() list order can override — list order only controls nesting within a single scope.
What's the difference between an interceptor and a guard for this kind of short-circuiting?
A guard's canActivate() returns a boolean before any interceptor runs at all — it rejects or allows the whole request, with no concept of wrapping a result. An interceptor wraps the Observable the handler (or the next interceptor) produces, so it can transform, log, cache, or replace that result, but by the time an interceptor runs, a guard has already allowed the request through.
Does ClassSerializerInterceptor have the same ordering rules?
Yes — it's a regular interceptor, usually bound via APP_INTERCEPTOR, so it sits at whatever scope you register it at and follows the same nesting as any other interceptor relative to others at different scopes.
Will a new NestJS version change this ordering?
The global → controller → method scope order and the onion composition are structural to how Nest builds the pipeline, not a detail that has changed across the 10.x–12.x line. Always verify behavior you depend on against the version you're running if it matters for production correctness.
Cheat sheet
| Task | Code | Notes |
|---|---|---|
| Define an interceptor | intercept(context: ExecutionContext, next: CallHandler): Observable<any> |
Must return an Observable, usually derived from next.handle()
|
| Run the handler | next.handle() |
Returns an Observable of the handler's (or next interceptor's) result |
| Transform the response | next.handle().pipe(map(data => ({ data }))) |
Runs after the handler, on the way back out |
| Log around the handler | next.handle().pipe(tap(() => log())) |
tap doesn't change the emitted value |
| Short-circuit (skip the handler) | return of(cachedValue) |
Never calls next.handle() — nothing nested inside this interceptor runs |
| Map errors | next.handle().pipe(catchError(() => throwError(() => new BadGatewayException()))) |
Only catches errors from inside next.handle(), not thrown before it |
| Add a timeout | next.handle().pipe(timeout(5000), catchError(mapTimeoutErr)) |
Stops waiting; does not cancel in-flight work the handler started |
| Bind at method/controller scope | @UseInterceptors(A, B) |
A wraps B: A is outer, B is inner |
| Bind globally, no DI | app.useGlobalInterceptors(new X()) |
Constructor dependencies cannot be injected |
| Bind globally, with DI |
{ provide: APP_INTERCEPTOR, useClass: X } in a module's providers
|
Outermost of all scopes; still goes through the container |
| Execution order (inbound) | global → controller → method → handler | Fixed; list order only applies within one scope |
| Execution order (outbound) | handler → method → controller → global | Exact reverse of inbound |
Key takeaways
-
@UseInterceptors(A, B)nestsAaroundB, not "A then B" — the first interceptor named is outermost. -
next.handle()invokes everything nested inside the current interceptor; skip it, and nothing inside that ring runs — including an interceptor that was supposed to apply to every response. - Global interceptors always wrap controller interceptors, which always wrap method interceptors. Scope order is fixed; list order only matters within a scope.
- A per-caller field (ownership, role, visibility) that's wrong specifically on a cache hit is a strong signal to check interceptor nesting before the data layer.
- Reach for
APP_INTERCEPTORthe moment an interceptor needs a constructor dependency —app.useGlobalInterceptors(new X())can't provide one.
🎮 Try it yourself
▶️ Open the interactive playground →
Runs right in your browser — poke at it and watch the concept react live.
Interceptor nesting is easier to see than to read about. The playground below lets you pick the order of a CacheInterceptor and an OwnershipInterceptor, send a simulated request from the document's owner followed by a request from a different user for the same document, and watch exactly which ring the second request never reaches.
🧠 Test yourself
Think it clicked? Take the 9-question quiz →
Instant feedback, a hint on every question, and an explanation for each answer — right or wrong.
This series has already covered two other pieces of the same request pipeline: how guards decide who reaches a handler, and the full middleware → guard → interceptor → pipe → handler order interceptors are one stop inside. If constructor injection into a provider like CacheStore isn't fully clear yet, the DI container episode builds that mental model from scratch.
So: has an interceptor you stacked ever produced a response that looked right for one caller and wrong for the next, with nothing in the data layer to blame? What gave it away first — the client, a test, or a support ticket?
📚 Read next
- NestJS 12 Lifecycle Hooks: The Order You Can't Assume
- NestJS 12: Standard Schema Validation Without class-validator
- NestJS Testing Module: Provider Overrides (with Cheat Sheet)
🚀 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:
- ⭐ GitHub — follow me and star the projects: github.com/parsajiravand
- 💬 Discord — join the frontend best-practices community: discord.gg/d9KRhuAwQ
- 📸 Instagram — frontend best practices, daily: @bestpractice___
Top comments (0)