Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Web Application Filters and Middleware

Use filters and middleware to add behavior around your handlers. A web application is a service that accepts an HTTP request, passes it through the configured pipeline, and returns a WebResponse. Like the rest of ntex, this pipeline uses Service and Middleware.

Filters and middleware work at different points in that pipeline:

  • A filter transforms an incoming WebRequest before processing continues.
  • Middleware wraps a service, so it can run code both before and after that service.

Both can use application state. Middleware services receive it through Ctx. A filter function can take it as its first argument. For the distinction between application state and request-local state, see Web Application State.

Choosing Between Them

For the notes API, keep path matching in routes and shared request policies in layers. A filter is a good place to turn credentials into a typed user value that handlers need. Middleware is a better fit for timing a complete operation, adding response headers, or serving a cached response. from_fn() is not a third kind of layer: it is a convenient way to write middleware without defining a wrapper struct.

Start with a closure for a small policy. Move to a named middleware type when configuration or service lifecycle behavior becomes substantial. You can attach either form to just the API scope, leaving a health check or public page outside that policy.

Filters

Use a filter to transform an incoming request before processing continues. Register application filters with App::filter(). For scopes and resources, use Scope::filter() and Resource::filter().

Each call appends a service to the inbound pipeline. A filter accepts WebRequest<In> and must return WebRequest<Out>:

WebRequest<In> -> filter -> WebRequest<Out>

Filters run in registration order. Each receives the previous filter’s output. If a filter returns an error, ntex skips the remaining filters, router, and handler. It renders the error through WebResponseError.

Request state is part of the WebRequest type, so filters can enforce requirements at compile time. An authentication filter can turn WebRequest<()> into WebRequest<AuthenticatedUser>. A handler expecting AuthenticatedUser can only be registered after a filter that provides it:

use std::convert::Infallible;
use ntex::web::{self, WebRequest};

struct AuthenticatedUser {
    id: u64,
}

async fn authenticate(
    req: WebRequest<()>,
) -> Result<WebRequest<AuthenticatedUser>, Infallible> {
    Ok(req.map_state(|()| AuthenticatedUser { id: 42 }))
}

async fn profile(_app: &(), user: AuthenticatedUser) -> String {
    format!("User {}", user.id)
}

web::App::default()
    .filter(authenticate)
    .route("/profile", web::get().to_with_state(profile));

Here, application state is (). The first argument to profile is &(). Its second argument is the AuthenticatedUser produced by the filter.

WebRequest::map_state() consumes the request, transforms its request-local state, and preserves the HTTP request and payload.

Extractors run only in the handler, so a filter sees the request body as a raw payload stream. It can replace that stream, for example to limit or decode every upload; see Streams in Filters and Middleware.

A filter can take application state as its first argument. It can return any error that implements WebResponseError. The error stops processing and becomes the response:

use ntex::web::{self, WebRequest, error};

fn main() {
    let app = web::App::default()
        .filter(async |_state: &(), req: WebRequest<()>| {
            if req.headers().contains_key("x-api-key") {
                Ok(req)
            } else {
                Err(error::ErrorForbidden("missing API key"))
            }
        })
        .route("/", web::get().to(async || "Hello"));
}

Filters run only on the way in. They cannot inspect or modify the handler’s response. Use middleware to wrap the complete request-response operation.

A filter’s successful output must be another WebRequest; it cannot return a successful response directly. Return an error to reject a request. Use middleware to return a response without running the inner service, such as for a cache hit, maintenance page, or authorization decision.

Middleware

Use middleware when you need to work with both requests and responses, or return a response without calling the inner service. A middleware component receives a service and wraps it with another service.

The wrapper can inspect or modify the request before calling the inner service through Ctx. It can then inspect or modify the response. Middleware can also change the request-state type before the call. A filter is usually simpler if you only need to process the request.

Middleware also sees bodies as streams. The request body has not been read by an extractor yet, and the response body is sent after the middleware returns. Streams in Filters and Middleware shows how to wrap either one.

To skip the inner service, return a WebResponse directly. Use WebRequest::into_response() to keep the original request attached to that response.

Register middleware on the application with App::middleware(). The corresponding methods on scopes and resources are Scope::middleware() and Resource::middleware(). You can install built-in middleware directly:

use ntex::web::{self, App, middleware};

App::default()
    .middleware(
        middleware::DefaultHeaders::new()
            .header("x-application", "example"),
    )
    .middleware(middleware::Logger::default())
    .route("/", web::get().to(async || "Hello"));

Middleware runs in registration order on the way in. Here, DefaultHeaders receives the request before Logger. The response travels in reverse order. Logger processes it before DefaultHeaders.

DefaultHeaders inserts a header only if the response does not already have one. Your handler can therefore override the default. Logger writes through the log facade. Install and configure a logger to see its output.

For custom middleware, start with an async closure passed to middleware::from_fn(). The closure receives the request and a Next handle. Call next.call(req) to run the inner service, or return a response without calling it to stop there.

Binding, readiness, and shutdown are forwarded automatically:

use ntex::http::header::{HeaderName, HeaderValue};
use ntex::web::{self, App, HttpResponse, middleware::from_fn};

web::HttpServer::new(async |_| {
    App::new()
        .middleware(from_fn(async |req, next| {
            if !req.headers().contains_key("authorization") {
                return Ok(req.into_response(HttpResponse::Unauthorized().build()));
            }
            let mut res = next.call(req).await?;
            res.headers_mut().insert(
                HeaderName::from_static("x-application"),
                HeaderValue::from_static("example"),
            );
            Ok(res)
        }))
        .route("/", web::get().to(async || "Hello"))
});

Rust infers the closure types once you pass the application to HttpServer or a test helper. To reject a request with any WebResponseError, return Err(web::WebError::from_err(err)).

To read application state, annotate the state type of next. For example, use next: Next<'_, _, AppState<Config>>, then call next.st().

fn_layer() from ntex::service is the protocol-independent equivalent. It works for any service. Web closures used with it need explicit request, response, and error types.

Checking an API Key and Returning 401

A missing credential should produce an intentional response, not merely fail a route guard. This example compares the key’s value and returns 401 before the handler runs. An outer DefaultHeaders layer labels both successful responses and these early rejections:

use std::{cell::Cell, rc::Rc};
use ntex::http::StatusCode;
use ntex::web::{self, HttpResponse, middleware::{self, from_fn}, test};

#[ntex::test]
async fn api_key_is_required() {
    let calls = Rc::new(Cell::new(0));
    let handler_calls = calls.clone();
    let app = test::init_service(
        web::App::new()
            .middleware(
                middleware::DefaultHeaders::new()
                    .header("x-application", "notes"),
            )
            .middleware(from_fn(async |req, next| {
                let valid = req.headers().get("x-api-key")
                    .and_then(|value| value.to_str().ok())
                    == Some("development-only");
                if !valid {
                    return Ok(req.into_response(
                        HttpResponse::Unauthorized().body("API key required"),
                    ));
                }
                next.call(req).await
            }))
            .route("/notes", web::get().to(async move || {
                handler_calls.set(handler_calls.get() + 1);
                "notes"
            })),
    )
    .await;

    for key in [None, Some("wrong"), Some("development-only")] {
        let mut request = test::TestRequest::get().uri("/notes");
        if let Some(key) = key {
            request = request.header("x-api-key", key);
        }
        let response = test::call_service(&app, request.to_request()).await;
        let expected = if key == Some("development-only") {
            StatusCode::OK
        } else {
            StatusCode::UNAUTHORIZED
        };
        assert_eq!(response.status(), expected);
        assert_eq!(response.headers().get("x-application").unwrap(), "notes");
    }
    assert_eq!(calls.get(), 1);
}

The hard-coded key is only a local demonstration. Load real credentials from application configuration or a secret store, do not log them, and protect them with HTTPS. A header’s presence alone is not authentication. If the handler needs the authenticated identity, use a filter that produces typed request-local state rather than repeating the credential check in each handler.

Returning Ok(req.into_response(...)) matters here: the rejection is already a response as it travels through outer middleware. Returning an error is also valid, but that error is normally rendered outside the application’s response middleware, as described in Errors and the Response Path.

Timing a Request

Measure around next.call() to observe how long the inner pipeline takes to produce its response. Copy the metadata you need before moving the request into that call. Here the middleware logs elapsed time and adds it to a header:

use std::time::Instant;
use ntex::http::header::{HeaderName, HeaderValue};
use ntex::web::{self, middleware::from_fn, test};

#[ntex::test]
async fn timing_adds_a_response_header() {
    let app = test::init_service(
        web::App::new()
            .middleware(from_fn(async |req, next| {
                let path = req.path().to_owned();
                let started = Instant::now();
                let result = next.call(req).await;
                let elapsed = started.elapsed().as_micros();
                log::info!("{path} completed in {elapsed} us");
                let mut response = result?;
                response.headers_mut().insert(
                    HeaderName::from_static("x-response-time-us"),
                    HeaderValue::try_from(elapsed.to_string()).unwrap(),
                );
                Ok(response)
            }))
            .route("/notes", web::get().to(async || "notes")),
    )
    .await;

    let response = test::call_service(
        &app, test::TestRequest::get().uri("/notes").to_request(),
    ).await;
    assert_eq!(response.status(), ntex::http::StatusCode::OK);
    let value = response.headers().get("x-response-time-us").unwrap();
    assert!(value.to_str().unwrap().parse::<u128>().is_ok());
}

The log runs for either an inner response or an inner service error; the header is added only when a response is available. Configure a log backend, such as env_logger, in the executable to see the message. Avoid logging sensitive query strings or credentials in a real access log.

This measures response creation, not the time needed to stream the response body to the client. A large download can continue after next.call() returns. To measure until the last byte, wrap the body as in Wrapping the Response Body. The built-in Logger already does this; use it when its access-log format fits your needs instead of maintaining a custom timing layer.

Built-In Response Layers

DefaultHeaders is useful for service labels and other fallback headers. It does not overwrite a header explicitly set by a handler, and it does not turn a 401 into a successful response. If your policy requires replacing a header unconditionally, use headers_mut().insert() after the inner call, as in the timing example.

With the compress feature enabled, middleware::Compress::default() negotiates response compression from Accept-Encoding. Register it before routes like the other middleware. It operates on the response body; request body decompression is a different concern. Streams in Filters and Middleware explains how Compress wraps the body and how a filter can decode uploads. For API responses, add compression only where it is useful rather than assuming it replaces sensible payload sizes or pagination.

A default Access-Control-Allow-Origin header alone is not a complete CORS policy. Browsers can send preflight OPTIONS requests, and authenticated cross-origin traffic needs a deliberate origin and credentials policy. ntex does not add OPTIONS routes automatically. Do not copy a wildcard header into an authentication example and assume that browser access is handled.

Writing a Middleware Service

Write a middleware struct and wrapper service if you need your own configuration type, your own readiness source, or a named service type. Middleware can control how the wrapped service reports readiness and shutdown. A filter implemented as a full Service also participates in both.

A custom middleware struct follows the normal ntex service model:

use ntex::http::header::{HeaderName, HeaderValue};
use ntex::web::{self, WebRequest, WebResponse};
use ntex::{Ctx, Middleware, Service};

struct ResponseHeader;

struct ResponseHeaderService<S> {
    service: S,
}

impl<S, St> Middleware<S, St> for ResponseHeader {
    type Service = ResponseHeaderService<S>;

    fn create(&self, _state: &St, service: S) -> Self::Service {
        ResponseHeaderService { service }
    }
}

impl<S, St, ReqSt> Service<St, WebRequest<ReqSt>>
    for ResponseHeaderService<S>
where
    S: Service<St, WebRequest<ReqSt>, Res = WebResponse>,
{
    type Res = WebResponse;
    type Error = S::Error;

    ntex::forward!(St, service);

    async fn call(
        &self,
        req: WebRequest<ReqSt>,
        ctx: Ctx<'_, Self, St>,
    ) -> Result<Self::Res, Self::Error> {
        let mut res = ctx.call(&self.service, req).await?;
        res.headers_mut().insert(
            HeaderName::from_static("x-application"),
            HeaderValue::from_static("example"),
        );
        Ok(res)
    }
}

web::App::default()
    .middleware(ResponseHeader)
    .route("/", web::get().to(async || "Hello"));

Middleware::create() runs when the application service is constructed. It receives application state and the service to wrap, then returns a wrapper for that service. The wrapper’s call() method receives a Ctx for each request.

If the wrapper needs to keep something from application state, clone an owned handle during create(). Do not try to retain the borrowed &St.

Always call the inner service through Ctx::call() to preserve call-time readiness checks. You must also forward bind(), ready(), and shutdown() to the wrapped service. Use forward! for standard forwarding. Implement these methods explicitly when you need custom behavior.

Without forwarding, the default implementations:

  • Report the middleware as always ready.
  • Do not register the inner service’s readiness notifications.
  • Never shut down the inner service.

The forward! macro takes the state type and one or more named or tuple fields. Add an optional trailing map_err = f to convert readiness errors. See Service pipelines for more on readiness and shutdown.

Configure Layers Before Routes

Add filters and middleware before registering services at each level. The first route, service, configuration callback, or default service moves the builder to its service-registration stage. You can no longer call filter() or middleware() after that:

use ntex::web::{self, middleware, App, WebRequest};

App::default()
    .middleware(middleware::Logger::default())
    .filter(async |req: WebRequest<()>| {
        Ok::<_, std::convert::Infallible>(req)
    })
    .route("/", web::get().to(async || "Hello"));

The same rule applies to Scope and Resource. See Builder Order.

Middleware and filters form separate stacks, even when you interleave their builder calls. All middleware at a level wraps that level’s complete filter-and-router service. It runs before every filter on the inbound path.

Checking Layer Order in a Test

Ordering affects more than log output. Put a response-header layer outside authentication if rejected requests need its headers too. Put timing outside both when you want to measure all of their work. The first middleware you register is the outermost one, unlike frameworks that reverse registration order.

This test records both sides of two middleware calls, so the inbound and outbound order are visible in one assertion:

use std::{cell::RefCell, rc::Rc};
use ntex::web::{self, middleware::from_fn, test};

#[ntex::test]
async fn middleware_runs_in_registration_order() {
    let events = Rc::new(RefCell::new(Vec::new()));
    let outer = events.clone();
    let inner = events.clone();
    let handler = events.clone();
    let app = test::init_service(
        web::App::new()
            .middleware(from_fn(async move |req, next| {
                outer.borrow_mut().push("outer in");
                let response = next.call(req).await?;
                outer.borrow_mut().push("outer out");
                Ok(response)
            }))
            .middleware(from_fn(async move |req, next| {
                inner.borrow_mut().push("inner in");
                let response = next.call(req).await?;
                inner.borrow_mut().push("inner out");
                Ok(response)
            }))
            .route("/", web::get().to(async move || {
                handler.borrow_mut().push("handler");
                "ok"
            })),
    )
    .await;

    let response = test::call_service(
        &app, test::TestRequest::get().uri("/").to_request(),
    ).await;
    assert_eq!(response.status(), ntex::http::StatusCode::OK);
    assert_eq!(&*events.borrow(), &[
        "outer in", "inner in", "handler", "inner out", "outer out",
    ]);
}

Keep the RefCell borrows confined to each push. None remains active over next.call().await, so overlapping requests cannot collide with a borrow held by a suspended middleware call. The event vector is a testing aid, not an access-log implementation.

Where Filters and Middleware Run

Choose where to install a layer based on which requests need it. You can add filters and middleware to an application, scope, or resource:

LevelRuns for
AppEvery request entering the application
ScopeRequests whose scope prefix and scope guards match
ResourceRequests whose resource path and resource guards match

For example, a request handled by a resource inside a scope follows this path:

application middleware
  -> application filters
  -> application routing and scope guards
  -> scope middleware
  -> scope filters
  -> scope routing and resource guards
  -> resource middleware
  -> resource filters
  -> route guards
  -> route handler

The response travels back through the middleware layers in reverse. At each level, middleware runs in registration order for the request and reverse registration order for the response. Filters are not part of the response path.

The router checks a scope or resource’s own guards before entering its middleware and filters. Application filters run before the application router chooses a scope or resource. Scope filters run before the scope router chooses a nested resource.

Route guards run later. The resource filter runs first. The resource then checks routes and their guards in registration order.

Fallback services run inside the layers of their level:

  • If no resource matches, the application default service runs after application middleware and filters.
  • If a scope matches but none of its services do, the scope default service runs after scope middleware and filters.
  • If a resource matches but no route does, its default service runs after resource middleware and filters. Without a custom default, it returns 405 Method Not Allowed.

See Web Applications and Routing for guard and fallback behavior.

Errors and the Response Path

Whether middleware can inspect an error response depends on where the error becomes a response. The route handler converts extractor failures and errors returned by handler Result values into WebResponse values. Response middleware can inspect or modify these responses normally.

Errors returned directly by filters, middleware services, or other web services stay as service errors while passing back through middleware. ntex renders them through WebResponseError outside the application middleware stack.

Middleware that propagates an inner error with ? does not see the final rendered response. To process that case, catch the error and convert it into a WebResponse within the middleware. See Web Application Errors for the error model.

Complete example with state-aware middleware and filters