Interceptors
Wrap a unit of work — observe it, decorate its reply, or answer in its place — in a single intercept(cx, next) call.
An interceptor wraps a unit: an HTTP request a route serves, a GraphQL
field, a WebSocket message, an MCP tool call, a job’s attempt, a tick, a
listener call. It sees the unit before the handler runs, holds the outcome
after, and in between calls next.run(cx) to run whatever sits inside it —
another interceptor, and eventually the handler. One call, both sides of the
boundary.
Interceptor is a Layer sub-trait in
nest_rs::core, edge-neutral: it reads the unit through its
execution context, the same UnitContext
a guard reads, and reaches an edge’s own view — the HTTP request and reply
through HttpView::of(cx) — when it needs one.
#[async_trait]pub trait Interceptor: Layer { async fn intercept(&self, cx: &mut UnitContext<'_>, next: Next<'_>) -> Outcome;}Outcome says whether the unit ran or was answered, and only running the rest
of the unit or answering it mints one: an interceptor that does neither does
not compile. next.run(cx) consumes next, so the rest of the unit runs once.
Same vocabulary as a guard, different shape:
- A guard runs before the handler and admits or refuses.
- An interceptor runs around it — it can time the call, add response headers, read what was answered, or answer in the handler’s place.
Install
Section titled “Install”cargo add nest-rsThe trait, #[interceptor] and the specs live in nest_rs::core, which every
build has: no feature turns them on.
A minimal interceptor
Section titled “A minimal interceptor”use nest_rs::core::{Interceptor, Layer, Next, Outcome, UnitContext, async_trait, injectable};use nest_rs::http::{HeaderValue, HttpView};
#[injectable]#[derive(Layer)]pub struct Tracer;
#[async_trait]impl Interceptor for Tracer { async fn intercept(&self, cx: &mut UnitContext<'_>, next: Next<'_>) -> Outcome { let outcome = next.run(cx).await; if let Some(resp) = HttpView::of(cx).ok().and_then(HttpView::response_mut) { resp.headers_mut().insert("x-trace", HeaderValue::from_static("hit")); } outcome }}A plain #[injectable] provider that implements Interceptor, bound for the
whole app, per controller or per handler: a module’s providers = [...] lists it,
unless the app’s list alone names it and
registers it. #[derive(Layer)] writes the Layer impl every interceptor
extends; #[layer(priority = -10)] beside it orders the interceptor ahead of
its stage’s others within one scope.
async_trait comes from nest_rs::core, as it does for guards: the trait is
declared under #[async_trait], and an async fn written without the same
macro no longer matches it (E0195).
The three scopes
Section titled “The three scopes”| Scope | Binding | Runs |
|---|---|---|
| Global | GlobalInterceptors<(Tracer,)> in the providers of the module the app boots | around every unit’s handler — a route, a field, a message, a tool call, a job, a tick, a listener call — after its guards |
| Host | #[use_interceptors(Tracer)] on the controller, resolver, gateway, MCP host or worker block | around each of its handlers |
| Per-handler | #[use_interceptors(Tracer)] beside a verb | around that handler |
#[controller(path = "/api")]#[use_interceptors(Tracer)]pub struct ApiController { #[inject] svc: Arc<ApiService>,}
#[routes]impl ApiController { #[get("/cache")] #[use_interceptors(CacheControl)] async fn cached(&self) -> Json<Snapshot> { /* ... */ }}Several interceptors in one attribute run outermost-first: the first listed sees the unit before the second, and its outcome wraps the second’s. The app’s global list runs outside the controller’s, which runs outside the handler’s.
TypeId dedup — redeclaration is free
Section titled “TypeId dedup — redeclaration is free”Like every other Layer, an Interceptor
declared globally and redeclared on the controller or method runs exactly
once per unit, at the broadest scope that declares it. See
Guards / Declare on the provider
for the worked example and the defense-in-depth argument.
The app’s list: GlobalInterceptors
Section titled “The app’s list: GlobalInterceptors”An interceptor around every handler is the app’s to choose, so the module the
app boots is the one place that says so: GlobalInterceptors<(…)> in its
providers, the first listed outermost. The pool registers what it lists unless
the app already does, so an interceptor is written once, and the module it sits
in may list it or not. The demo’s API audits every write it admits that way:
#[injectable]pub struct AuditInterceptor;
impl Layer for AuditInterceptor { fn serves(&self, unit: Unit) -> bool { unit.edge() == Some(Edge::Http) }}
#[async_trait]impl Interceptor for AuditInterceptor { async fn intercept(&self, cx: &mut UnitContext<'_>, next: Next<'_>) -> Outcome { let outcome = next.run(cx).await; // … outcome }}#[module( imports = [ // … AuditHttpModule, // … ], providers = [GlobalInterceptors<(AuditInterceptor,)>],)]pub struct ApiModule;serves is read once, as the app-wide list is composed for a site: a unit of
another edge never runs it. What the interceptor injects is held to the imports
of the module the app boots, and one the pool cannot build, or that is not a
singleton, fails the boot naming it, as does a pool a module the app imports
declares, or a second one. A singleton provider of yours injecting the interceptor
needs it listed in a module’s providers: a pool registers what it alone lists once
every module is built, and the boot says so.
A bare #[interceptor] does not compile, and its refusal names this list:
importing a feature’s module never adds a layer around every handler of your app.
The unit stage: #[interceptor(stage = unit)]
Section titled “The unit stage: #[interceptor(stage = unit)]”Every interceptor above runs after the guards and the posture’s class
gate: a caching interceptor can never answer a caller the route refuses. The
one opening is an interceptor its module declares at the unit stage, around
the guards, which importing that module brings to every unit, with no line in
the module the app boots — it is how a capability such as Server-Timing needs
nothing but its import:
use nest_rs::core::{Interceptor, Layer, Next, Outcome, UnitContext, async_trait, interceptor};
#[interceptor(stage = unit)]#[derive(Layer)]pub struct Timing;
#[async_trait]impl Interceptor for Timing { async fn intercept(&self, cx: &mut UnitContext<'_>, next: Next<'_>) -> Outcome { next.run(cx).await }}It runs on every HTTP unit — a route, a self-mount’s request (/graphql,
/mcp, a gateway’s upgrade, the OpenAPI document) and what the router answers
itself (a 404, a 405) — on every WebSocket message, one no handler reads
among them, once around every operation an /mcp request carries, and around every job’s attempt, tick and
listener call; it observes what the guards refused. It is the
place for what must see every answer: Server-Timing and the RFC 9728
challenge nest-rs-oauth-resource adds to a 401 sit there. Writing
stage = unit is the visible line that opens it; an app-listed global
interceptor never runs before the access decision.
Around a GraphQL field
Section titled “Around a GraphQL field”Each root field of a GraphQL operation is a unit of its own, graphql.field,
and the app’s, the resolver’s and the field’s own interceptors run around it as
around a route: Interceptors beyond HTTP.
What an interceptor cannot change
Section titled “What an interceptor cannot change”The data unit of work wraps the whole pipeline, guards included, and commits
on the unit’s own outcome. An interceptor changes what the client reads,
never whether the unit failed: once the rest of the unit failed, an Ok an
interceptor returns stays a failure — answered with its reply, the original
error kept, one warn naming the interceptor — so a failed request still
rolls its writes back.
Common things an interceptor does
Section titled “Common things an interceptor does”- Decorate the reply — headers (
Server-Timing,X-Cache-Status), read throughHttpView::of(cx)?.response_mut()oncenext.run(cx)returned. The request is still there beside it, its head and extensions whole: only its body is gone once the handler read it. - Time the call — measure latency by route, emit a metric.
- Answer instead — a cache answers through
HttpView::of(cx)?.respond(..)and returns itsSettledwithout running the rest of the unit. A GraphQL field has no reply an interceptor writes: its value is typed, so it fails the field or runs it. An MCP operation has no reply an interceptor writes either. - Audit — record what the unit answered, as the demo’s posts controller does.
The trace, the actor_id and the request scope are not on that list: the edge
installs them before any layer runs, see
Correlation.
Reference
Section titled “Reference”posts/http/interceptor.rsin the demo — an audit interceptor on the posts controller.
Going further
Section titled “Going further”- The request lifecycle — where each stage runs.
- Guards — the stage the handler-stage interceptors run after.
- Error handling — answering a failure rather than wrapping a unit.
- Database / transactions — the unit of work around every stage.