Middleware
NestRS has no middleware primitive — Guards and Interceptors cover the two roles. A short guide for readers looking for it.
NestRS doesn’t have a middleware primitive. Some backend frameworks ship one for cross-cutting work; NestRS splits the responsibility so the shape of each layer is explicit:
- Gate-and-context work lives in Guards —
pre-handler, can short-circuit with a response, can attach typed
context the handler reads back via
Ambient<T>. - Wrap-the-handler work lives in Interceptors — observe both sides, install ambient state, transform the response.
- Work around every request, before the access decision — what a
pre-routing middleware usually does — is an interceptor its module declares
at the unit stage,
#[interceptor(stage = unit)]: it sees every unit, refusals and404s included.
If you’re looking for a place to put work the word “middleware” usually covers — logging, request id, rate limiting, auth, opening a transaction — the table below maps the role to its NestRS home.
What the word usually covers, and where it lands in NestRS
Section titled “What the word usually covers, and where it lands in NestRS”| Role | NestRS primitive | Why |
|---|---|---|
| Logging the request | Interceptor | Needs both sides (start time, end time, status) |
Timing every answer, refusals and 404s included | Unit-stage interceptor, #[interceptor(stage = unit)] | Runs around the guards, so it sees what they refuse |
Adding a X-Cache-Status header to the response | Interceptor | Touches the response |
| Authenticating the bearer token | Guard (AuthnGuard) | Short-circuit on 401, attach Claims for the handler |
| Rate-limiting | Guard | Short-circuit on 429 before any work runs |
| Parsing/normalizing the body | Pipe at the boundary | Pure transform, no DI |
| Opening a database transaction | Nothing to write | Importing the database binding runs every request as a unit of work, committed on its outcome |
| Stamping a request / correlation id | Nothing to write | Every unit of work already runs under a W3C trace |
| CORS, security headers | The transport, configured on HttpConfig | Lower-level than a Guard/Interceptor |
The split is on purpose: “gate” and “wrap” are different shapes, the framework names them differently, and the request-layer ordering reflects the difference.
“But I want a middleware”
Section titled ““But I want a middleware””Three shapes cover it. Pick the one that matches.
“I want to see every request and add a header to the response.”
Section titled ““I want to see every request and add a header to the response.””That’s an interceptor.
#[injectable]#[derive(Layer)]pub struct NoIndex;
#[async_trait]impl Interceptor for NoIndex { 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-robots-tag", HeaderValue::from_static("noindex")); } outcome }}Bind it for the whole app by listing GlobalInterceptors<(NoIndex,)> in the
providers of the module the app boots. It runs after the guards, so a refused
request never reaches it; an interceptor that must see every answer, refusals
and 404s included, is declared #[interceptor(stage = unit)].
Do not write this one to stamp a correlation id: the framework already runs
every request under a trace and reports it as
traceresponse. A hand-stamped id correlates with nothing the logs, the access
line or a queued job are filed under.
“I want to validate the request before any handler runs and block it if invalid.”
Section titled ““I want to validate the request before any handler runs and block it if invalid.””That’s a guard. Gate the request, return Err(Denial) on rejection.
use nest_rs::core::{Layer, UnitContext, async_trait, injectable};use nest_rs::guards::{Denial, Guard, GuardFor};use nest_rs::http::HttpView;use nest_rs::guards::GuardPhase;
#[injectable]#[derive(Layer)]pub struct RequireApiKey;
#[async_trait]impl Guard for RequireApiKey { fn phase(&self) -> GuardPhase { GuardPhase::Authentication }
async fn check_http(&self, cx: &mut UnitContext<'_>) -> Result<(), Denial> { HttpView::of(cx)? .request() .header("x-api-key") .is_some() .ok_or_else(|| Denial::unauthorized("missing key")) }
async fn check(&self, _cx: &mut UnitContext<'_>) -> Result<(), Denial> { Ok(()) }}
impl GuardFor<HttpView> for RequireApiKey {}Bind with #[use_guards(RequireApiKey)] per controller or per handler,
or globally by listing GlobalGuards<(RequireApiKey,)> in the module the app
boots. The key is
the request’s, so check_http decides it, and check admits the GraphQL
fields, WebSocket messages and MCP operations a checked request carries: the
global pool runs check on each of them, where there is no HTTP request to
read.
“I want to attach something to the request so the handler can read it.”
Section titled ““I want to attach something to the request so the handler can read it.””A guard does that too: it attaches the value, which is ambient for the rest of the request once the guards passed:
#[async_trait]impl Guard for AuthnGuard { fn phase(&self) -> GuardPhase { GuardPhase::Authentication }
async fn check_http(&self, cx: &mut UnitContext<'_>) -> Result<(), Denial> { let claims = verify_bearer(HttpView::of(cx)?.request()) .map_err(|_| Denial::unauthorized("invalid token"))?; cx.attach(claims); Ok(()) }
async fn check(&self, _cx: &mut UnitContext<'_>) -> Result<(), Denial> { Ok(()) }}
impl GuardFor<HttpView> for AuthnGuard {}
// In the handler:async fn me(&self, auth: Ambient<Claims>) -> Json<User> { /* ... */ }What about raw HTTP middleware?
Section titled “What about raw HTTP middleware?”nest-rs-http serves requests itself, on hyper,
and has no lower-level middleware trait: the named categories
(Guard / Interceptor / Exception filter) are the layers. CORS, request-size
limits, body-decoding — those things live on HttpConfig and are
applied by the transport around every route, not as NestRS Guards or
Interceptors.
nest-rs-http owns the endpoint, which is what makes every layer
go through DI and the access graph — portable across controllers and
checkable at boot. A middleware written for another HTTP library ports to an
Interceptor in a few lines and gains both: it wraps the handler the
same way, with DI and the access graph on top. The lower-level knobs
such middleware is often reached for — CORS, TLS, body-size limits,
request timeout — are already HttpConfig fields.
Going further
Section titled “Going further”- Guards — gate and attach context.
- Interceptors — wrap and observe.
- Pipes — pure input transforms.
- HTTP / configuration — CORS, TLS, the
framework
Server:header.