Skip to content

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.

nest_rs::core::Interceptor
#[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.
Terminal window
cargo add nest-rs

The trait, #[interceptor] and the specs live in nest_rs::core, which every build has: no feature turns them on.

apps/api/src/interceptor.rs
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).

ScopeBindingRuns
GlobalGlobalInterceptors<(Tracer,)> in the providers of the module the app bootsaround 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 blockaround each of its handlers
Per-handler#[use_interceptors(Tracer)] beside a verbaround that handler
crates/features/src/api/http/controller.rs
#[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.

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.

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:

crates/features/src/audit/http/interceptor.rs (from the demo, abridged)
#[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
}
}
apps/api/src/module.rs (from the demo, abridged)
#[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:

crates/features/src/timing/interceptor.rs
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.

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.

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.

  • Decorate the reply — headers (Server-Timing, X-Cache-Status), read through HttpView::of(cx)?.response_mut() once next.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 its Settled without 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.