actixutils

middleware — Examples

Focused, standalone snippets for each middleware in the module. Unlike TUTORIALS.md, these don’t build on each other — copy whichever section you need.


Auth<T> — JWT bearer authentication

use actix_web::{web, App};
use actixutils::locals::{HS256Signer, Identity, Validate};
use actixutils::middleware::Auth;
use std::sync::Arc;

let signer: Arc<dyn Validate<Identity>> =
    Arc::new(HS256Signer::new("svc".to_string(), "secret".to_string()));

App::new().service(
    web::scope("/api")
        .wrap(Auth { validator: signer })
        .route("/me", web::get().to(me_handler)),
);
# async fn me_handler() -> actix_web::HttpResponse { actix_web::HttpResponse::Ok().finish() }

Reading the claims in a handler:

use actix_web::{HttpRequest, HttpMessage, HttpResponse};
use actixutils::locals::Identity;

async fn me_handler(req: HttpRequest) -> HttpResponse {
    match req.extensions().get::<Identity>() {
        Some(identity) => HttpResponse::Ok().json(identity),
        None => HttpResponse::InternalServerError().finish(), // shouldn't happen if Auth ran
    }
}

Token source: Authorization: Bearer <token> header, or an access_token cookie as a fallback. Missing token or a failed validate() call both result in 401 Unauthorized.


ResponseEqualizer — timing-attack mitigation

use actixutils::middleware::ResponseEqualizer;
use actix_web::{web, App};
use std::time::Duration;

App::new().service(
    web::scope("/auth")
        .wrap(ResponseEqualizer::with_jitter(
            Duration::from_millis(150), // every response takes at least 150ms
            Duration::from_millis(50),  // plus up to 50ms of random jitter
        ))
        .route("/login", web::post().to(login_handler)),
);
# async fn login_handler() -> actix_web::HttpResponse { actix_web::HttpResponse::Ok().finish() }

Use ResponseEqualizer::new(min_duration) instead if you don’t want jitter — useful on login, password-reset, or “does this account exist” endpoints where response latency alone could reveal whether a lookup short-circuited. Pick a minimum comfortably above your slowest legitimate path, otherwise slow requests still stand out. Padding is applied to responses that come back normally; an error raised by an inner middleware skips it.


RateLimiter<T> — sliding-window rate limiting

RateLimiter::new takes a backing Arc<dyn ferrumec::Store<T::Id, VecDeque<Instant>>> — there’s no default in-memory store shipped with the crate, so supply a small one (a HashMap behind an RwLock is enough for a single process). The key type must implement GetId; here it’s keyed on the crate’s built-in ClientIp extractor (see ClientIpMiddleware below for how ClientIp gets populated). For per-user limits, key on a small local extractor that reads the authenticated Identity (see TUTORIALS.md §3).

use actixutils::extractors::ClientIp;
use actixutils::locals::ProxyConfig;
use actixutils::middleware::{ClientIpMiddleware, RateLimiter};
use actix_web::{web, App};
use async_trait::async_trait;
use ferrumec::Store;
use std::collections::{HashMap, VecDeque};
use std::error::Error;
use std::net::IpAddr;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::RwLock;

struct MemoryRateStore {
    inner: RwLock<HashMap<IpAddr, VecDeque<Instant>>>,
}

#[async_trait]
impl Store<IpAddr, VecDeque<Instant>> for MemoryRateStore {
    async fn get(&self, key: &IpAddr) -> Result<Option<VecDeque<Instant>>, Box<dyn Error>> {
        Ok(self.inner.read().await.get(key).cloned())
    }
    async fn set(&self, key: &IpAddr, value: VecDeque<Instant>) -> Result<(), Box<dyn Error>> {
        self.inner.write().await.insert(*key, value);
        Ok(())
    }
    async fn delete(&self, key: &IpAddr) -> Result<(), Box<dyn Error>> {
        self.inner.write().await.remove(key);
        Ok(())
    }
    async fn clear(&self) -> Result<(), Box<dyn Error>> {
        self.inner.write().await.clear();
        Ok(())
    }
}

let store = Arc::new(MemoryRateStore { inner: RwLock::new(HashMap::new()) });

App::new().service(
    web::scope("/public")
        // Last `.wrap()` runs first: ClientIpMiddleware must populate ClientIp
        // before RateLimiter extracts it.
        .wrap(RateLimiter::<ClientIp>::new(store, 20, Duration::from_secs(60)))
        .wrap(ClientIpMiddleware::new(ProxyConfig::new(vec![])))
        .route("/search", web::get().to(search_handler)),
);
# async fn search_handler() -> actix_web::HttpResponse { actix_web::HttpResponse::Ok().finish() }

Requests over the limit receive 429 Too Many Requests and never reach search_handler. If the identity extractor itself fails (e.g. ClientIp without ClientIpMiddleware having run, or a JWT-based key with no valid token), the request is not rejected by RateLimiter — it passes through unlimited, so pair it with an auth middleware (or ClientIpMiddleware, as above) if you need requests without a resolvable identity blocked outright. Also note that ClientIpMiddleware inserts nothing when a connection has no peer address, which makes the extractor fail the same way.


Idempotency<Store> — safe request deduplication

use actixutils::middleware::Idempotency;
use actixutils::locals::{IdempotencyStore, IdempotencyState, CachedResponse};
use actix_web::{web, App};
use async_trait::async_trait;
use std::{sync::Arc, time::Duration};

struct RedisIdempotencyStore { /* ... */ }

#[async_trait]
impl IdempotencyStore for RedisIdempotencyStore {
    type Error = std::io::Error;

    async fn acquire(&self, key: &str, ttl: Duration) -> Result<bool, Self::Error> {
        // SETNX key "in_progress" EX ttl
        Ok(true)
    }
    async fn get(&self, key: &str) -> Result<Option<IdempotencyState>, Self::Error> {
        Ok(None)
    }
    async fn complete(&self, key: &str, response: CachedResponse) -> Result<(), Self::Error> {
        Ok(())
    }
    async fn release(&self, key: &str) -> Result<(), Self::Error> {
        Ok(())
    }
}

let store = Arc::new(RedisIdempotencyStore { /* ... */ });

App::new().service(
    web::scope("/payments")
        .wrap(
            Idempotency::new(store)
                .ttl(Duration::from_secs(86_400))     // default is 1 hour
                .header("Idempotency-Key"),            // this is also the default
        )
        .route("/charge", web::post().to(charge_handler)),
);
# async fn charge_handler() -> actix_web::HttpResponse { actix_web::HttpResponse::Ok().finish() }

Client usage — send the same key on retry:

POST /payments/charge
Idempotency-Key: 6c1b1c1e-2f2a-4c9a-9c2e-3a1f7e9d0b21

{"amount_cents": 2500, "currency": "usd"}

RequestId — per-request correlation id

use actixutils::middleware::RequestId;
use actix_web::{web, App};

App::new()
    .wrap(RequestId)
    .route("/ping", web::get().to(ping));
# async fn ping() -> actix_web::HttpResponse { actix_web::HttpResponse::Ok().finish() }

Reading it downstream:

use actixutils::middleware::RequestIdStr;
use actix_web::{HttpRequest, HttpResponse, HttpMessage};

async fn handler(req: HttpRequest) -> HttpResponse {
    if let Some(rid) = req.extensions().get::<RequestIdStr>() {
        tracing::info!(request_id = %rid.0, "handling request");
    }
    HttpResponse::Ok().finish()
}

Every response also gets an X-Request-Id header automatically, and the id is recorded on the current tracing::Span as the request_id field (your span must declare that field, e.g. #[tracing::instrument(fields(request_id))], for the recording to take effect).


Context / ReadContext<T> — event-publishing context

Depends on RequestId and an auth middleware having already populated extensions, so register ReadContext first (innermost) and RequestId last (outermost). T must implement locals::GetId (already done for Identity and Authority).

use actixutils::locals::Authority;
use actixutils::middleware::{Auth, Context, ReadContext, RequestId};
use actix_web::{web, App, HttpRequest, HttpResponse, HttpMessage};
use std::sync::Arc;

App::new()
    .wrap(ReadContext::<Authority>::new(event_stream.clone(), "orders-svc".into())) // 3. runs last
    .wrap(Auth::<Authority> { validator: signer.clone() })                          // 2. inserts Authority
    .wrap(RequestId)                                                                // 1. runs first
    .route("/orders", web::post().to(create_order));

async fn create_order(req: HttpRequest) -> HttpResponse {
    let ctx = req.extensions().get::<Context>().cloned();
    if let Some(ctx) = ctx {
        // ctx.publish(order_created_event).await; // an `Event<T>` from ferrumec
    }
    HttpResponse::Ok().finish()
}
# let signer: Arc<dyn actixutils::locals::Validate<Authority>> = unimplemented!();
# let event_stream: Arc<dyn ferrumec::EventStream> = unimplemented!();

ReadContext::new takes the shared event-stream handle and a producer name that gets embedded in every published event’s metadata. Chain .with_user_as_audience(true) if events published in this context should also be routed to the acting user (e.g. for a personal activity feed). Context::publish logs failures with tracing::error! instead of returning them, so a broken event bus never fails the request. If RequestId or the identity is missing, ReadContext responds with 500.


Pagination / PaginationMiddleware — task-local list params

use actixutils::middleware::PaginationMiddleware;
use actixutils::locals::Pagination;
use actix_web::{web, App, HttpResponse};

App::new().service(
    web::scope("/items")
        .wrap(PaginationMiddleware)
        .route("", web::get().to(list_items)),
);

async fn list_items() -> HttpResponse {
    let p = Pagination::get();
    HttpResponse::Ok().json(serde_json::json!({ "page": p.page, "limit": p.limit }))
}

GET /items?page=2&limit=25 → Pagination { page: 2, limit: 25 }. GET /items (no query params) → defaults of page: 0, limit: 100. Pagination::offset() returns page * limit.

limit is not capped, and page * limit is plain u32 arithmetic, so clamp both before using them in a query:

let p = actixutils::locals::Pagination::get();
let limit = p.limit.min(200);
let offset = (p.page as u64 * limit as u64).min(i64::MAX as u64);

Session<T> and ReadSession<T> live in actixutils::extractors (re-exported as actixutils::Session and actixutils::ReadSession); the middleware lives in actixutils::middleware. All are generic over your own session type T. The middleware is backed by ferrumec::Store<Uuid, T>, the same trait family used by RateLimiter; there is no separate session-store trait.

use actixutils::Session;
use actixutils::middleware::SessionMiddleware;
use actix_web::{web, App, HttpResponse};
use async_trait::async_trait;
use ferrumec::Store;
use std::{collections::HashMap, error::Error, sync::Arc};
use tokio::sync::RwLock;
use uuid::Uuid;

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
struct CartSession {
    item_ids: Vec<String>,
}

#[derive(Default)]
struct InMemorySessionStore {
    data: RwLock<HashMap<Uuid, CartSession>>,
}

#[async_trait]
impl Store<Uuid, CartSession> for InMemorySessionStore {
    async fn get(&self, session_id: &Uuid) -> Result<Option<CartSession>, Box<dyn Error>> {
        Ok(self.data.read().await.get(session_id).cloned())
    }
    async fn set(&self, session_id: &Uuid, session: CartSession) -> Result<(), Box<dyn Error>> {
        self.data.write().await.insert(*session_id, session);
        Ok(())
    }
    async fn delete(&self, session_id: &Uuid) -> Result<(), Box<dyn Error>> {
        self.data.write().await.remove(session_id);
        Ok(())
    }
    async fn clear(&self) -> Result<(), Box<dyn Error>> {
        self.data.write().await.clear();
        Ok(())
    }
}

let store: Arc<dyn Store<Uuid, CartSession>> = Arc::new(InMemorySessionStore::default());

App::new()
    .wrap(SessionMiddleware::new(store).cookie_name("cart_session"))
    .route("/cart/add", web::post().to(add_to_cart));

async fn add_to_cart(session: Session<CartSession>) -> HttpResponse {
    let mut cart = session.write().await; // marks the session dirty
    cart.item_ids.push("sku-123".into());
    HttpResponse::Ok().finish()
}

Read-only access with ReadSession<T>

ReadSession<T> holds an owned read lock and derefs straight to T, so handlers that only look at the session need no .await:

use actixutils::ReadSession;

async fn cart_size(cart: ReadSession<CartSession>) -> HttpResponse {
    HttpResponse::Ok().body(cart.item_ids.len().to_string())
}

Don’t call Session::write() in the same handler while a ReadSession guard is still alive: the write waits for the read lock to be released, which never happens, so the request hangs.

Sessions that must already exist: RequiredSession<T>

use actixutils::middleware::RequiredSession;

let store: Arc<dyn Store<Uuid, CartSession>> = Arc::new(InMemorySessionStore::default());

web::scope("/account")
    .wrap(RequiredSession::new(store).cookie_name("cart_session"))
    .route("/cart", web::get().to(cart_size));

A missing cookie, an unparseable ID, or an ID that is not in the store is 401 Unauthorized. RequiredSession never creates sessions or sets cookies, and T only needs Clone (no Default). Create the session elsewhere, for example in a login handler that generates a Uuid, calls store.set(...), and sets the cookie itself.


AttachLocal<T> / SetLocal — generic scoped extraction

Use this when you want the same “extract once, expose everywhere via a task-local” pattern that PaginationMiddleware uses, but for your own type.

use actixutils::middleware::AttachLocal;
use actix_web::{web, App, FromRequest, HttpRequest, dev::Payload};
use std::future::Future;

#[derive(Clone)]
struct TenantId(String);

tokio::task_local! {
    static TENANT: TenantId;
}

impl actixutils::middleware::SetLocal for TenantId {
    fn scope<F: Future>(self, fut: F) -> impl Future<Output = F::Output> {
        TENANT.scope(self, fut)
    }
}

impl FromRequest for TenantId {
    type Error = actix_web::Error;
    type Future = std::future::Ready<Result<Self, Self::Error>>;

    fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future {
        let tenant = req
            .headers()
            .get("X-Tenant-Id")
            .and_then(|v| v.to_str().ok())
            .unwrap_or("default")
            .to_string();
        std::future::ready(Ok(TenantId(tenant)))
    }
}

App::new().service(
    web::scope("/api")
        .wrap(AttachLocal::<TenantId>::new())
        .route("/data", web::get().to(get_data)),
);

async fn get_data() -> actix_web::HttpResponse {
    let tenant = TENANT.try_with(|t| t.0.clone()).unwrap_or_else(|_| "unknown".into());
    actix_web::HttpResponse::Ok().body(tenant)
}

If T::from_request fails, the error is converted into an actix_web::Error and the request is rejected before the downstream service ever runs.


identity / authority(bit) — Next-style JWT guards

(Requires the jwt feature.) Alternative to Auth<T> for cases where you want route-level from_fn gating rather than a Transform-based middleware.

use actixutils::middleware::{identity, authority};
use actix_web::{web, middleware::from_fn, App};

App::new().service(
    web::scope("/api")
        .wrap(from_fn(identity)) // require any valid Identity JWT
        .route("/profile", web::get().to(profile_handler))
        .service(
            web::scope("/billing")
                .wrap(from_fn(authority(3))) // additionally require permission bit 3
                .route("/invoices", web::get().to(invoices_handler)),
        ),
);
# async fn profile_handler() -> actix_web::HttpResponse { actix_web::HttpResponse::Ok().finish() }
# async fn invoices_handler() -> actix_web::HttpResponse { actix_web::HttpResponse::Ok().finish() }

identity fails with 401 Unauthorized (raised by the underlying Jwt<Identity> extractor) if the token is missing or invalid. authority(n) fails with 401 under the same conditions, or 403 Forbidden if the token is valid but bit n of Authority::role isn’t set.


PathParams — unify path and query parameters

PathParams builds a Filters map from the query string, overlays the matched path parameters on top (a path parameter wins over a query parameter of the same name), and stores it in the request extensions.

use actixutils::extractors::Filters;
use actixutils::middleware::PathParams;
use actix_web::{web, App, HttpResponse};

App::new().service(
    web::resource("/users/{id}")
        .wrap(PathParams)
        .route(web::get().to(get_user)),
);

async fn get_user(filters: Filters) -> HttpResponse {
    // GET /users/42?id=ignored&verbose=1  →  {"id": "42", "verbose": "1"}
    let id = filters.get("id").cloned().unwrap_or_default();
    HttpResponse::Ok().body(id)
}

Filters also works as a plain extractor without the middleware: it then collects just the query-string pairs into a HashMap<String, String>. It returns 400 Bad Request if the query string cannot be parsed. Attach PathParams where the dynamic segments have already been matched (the resource or the scope that owns them) so they appear in the map. Filters derefs to HashMap<String, String>, and can be built from a map with Filters::from or the crate’s filters! macro.


Singleflight<K, KeyFn> — request coalescing

Groups concurrent requests that map to the same key so only one of them actually reaches the wrapped service; the rest wait and receive a cloned copy of the leader’s response.

use actixutils::middleware::Singleflight;
use actix_web::{web, App};

App::new().service(
    web::scope("/reports")
        .wrap(Singleflight::new(|req: &actix_web::dev::ServiceRequest| {
            // Coalesce by path + query, so two clients requesting the same
            // expensive report at once only compute it once.
            req.uri().to_string()
        }))
        .route("/{name}", web::get().to(generate_report)),
);
# async fn generate_report() -> actix_web::HttpResponse { actix_web::HttpResponse::Ok().finish() }

The response body is fully buffered so it can be cloned to every follower, so this is best suited to endpoints with bounded, non-streaming responses (e.g. an expensive read that several clients might request at once) rather than large downloads. If the leader’s execution errors, panics, or is cancelled, all waiting followers receive an error instead of hanging forever.


TimeoutMiddleware — per-request deadline

use actixutils::middleware::TimeoutMiddleware;
use actix_web::{web, App};
use std::time::Duration;

App::new().service(
    web::scope("/slow-integration")
        .wrap(TimeoutMiddleware::new(Duration::from_secs(5)))
        .route("/sync", web::post().to(sync_handler)),
);
# async fn sync_handler() -> actix_web::HttpResponse { actix_web::HttpResponse::Ok().finish() }

If sync_handler (plus anything else in the wrapped chain) hasn’t produced a response within 5 seconds, the in-flight future is dropped and the client receives 504 Gateway Timeout instead. Because the future is dropped rather than awaited to completion, work the handler already did (database writes, outbound calls) is not rolled back.


ClientIpMiddleware — client IP / trusted-proxy resolution

Resolves the real client IP even when requests pass through one or more reverse proxies, without blindly trusting a spoofable X-Forwarded-For header from just anyone.

use actixutils::extractors::ClientIp;
use actixutils::locals::ProxyConfig;
use actixutils::middleware::ClientIpMiddleware;
use actix_web::{web, App, HttpResponse};

let proxy_config = ProxyConfig::new(vec![
    "10.0.0.0/8".parse().unwrap(),      // internal load balancer subnet
    "172.16.0.0/12".parse().unwrap(),
]);

App::new()
    .wrap(ClientIpMiddleware::new(proxy_config))
    .route("/whoami", web::get().to(whoami));

async fn whoami(ip: ClientIp) -> HttpResponse {
    HttpResponse::Ok().body(ip.ip().to_string())
}