Introduction

Actix-web middleware wraps handlers in reverse order of registration: the last middleware added is the first to execute. This means request processing goes through middleware in reverse order, and response processing goes through them in forward order. Misunderstanding this causes authentication to run before CORS preflight handling, logging to miss error responses, and compression to apply to already-encoded bodies.

Symptoms

  • CORS preflight requests (OPTIONS) rejected before reaching CORS middleware
  • Authentication middleware runs before request body is parsed
  • Request logging does not capture response status code or duration
  • Compression middleware double-encodes already compressed responses
  • Error handler middleware cannot catch errors from upstream middleware

Debug middleware order: ```rust // Add logging middleware to see execution order use actix_web::{dev::ServiceRequest, dev::ServiceResponse, Error, HttpMessage};

async fn log_middleware( req: ServiceRequest, srv: &impl actix_web::dev::Service<ServiceRequest, Response = ServiceResponse, Error = Error>, ) -> Result<ServiceResponse, Error> { eprintln!(">>> ENTERING log_middleware: {:?}", req.path()); let res = srv.call(req).await?; eprintln!("<<< EXITING log_middleware: {:?}", res.status()); Ok(res) } ```

Common Causes

  • Assuming middleware runs in registration order (it is reverse)
  • CORS middleware registered after authentication middleware
  • Logger middleware registered too late to capture full request lifecycle
  • Custom middleware not implementing proper call chain
  • Multiple .wrap() calls creating nested wrapping

Step-by-Step Fix

  1. 1.Register middleware in correct reverse order:
  2. 2.```rust
  3. 3.use actix_web::{web, App, HttpServer, middleware};

#[actix_web::main] async fn main() -> std::io::Result<()> { HttpServer::new(|| { App::new() // 1. FIRST to execute on request (LAST registered) // Logger runs first to capture full timing .wrap(middleware::Logger::default()) // 2. SECOND to execute // CORS handles preflight before auth .wrap(Cors::permissive()) // 3. THIRD to execute // Auth runs after CORS, before handler .wrap(AuthMiddleware) // 4. Compressor runs closest to handler .wrap(middleware::Compress::default()) // 5. Error handler wraps innermost .wrap(middleware::ErrorHandlers::new()) // Routes .service(web::resource("/api/users").route(web::get().to(get_users))) }) .bind("127.0.0.1:8080")? .run() .await }

// Execution order for REQUEST: // Logger -> CORS -> Auth -> Compress -> ErrorHandlers -> Handler // // Execution order for RESPONSE: // Handler -> ErrorHandlers -> Compress -> Auth -> CORS -> Logger ```

  1. 1.Fix CORS preflight being rejected by auth:
  2. 2.```rust
  3. 3.use actix_cors::Cors;
  4. 4.use actix_web::http::header;

// WRONG - auth runs before CORS, rejects OPTIONS preflight App::new() .wrap(AuthMiddleware) // Runs SECOND (rejects OPTIONS) .wrap(Cors::default()) // Runs FIRST (too late)

// CORRECT - CORS handles preflight before auth App::new() .wrap(Cors::default() .allowed_origin("https://example.com") .allowed_methods(vec!["GET", "POST", "PUT", "DELETE"]) .allowed_headers(vec![ header::AUTHORIZATION, header::ACCEPT, header::CONTENT_TYPE, ]) .max_age(3600), ) // Runs FIRST (handles OPTIONS) .wrap(AuthMiddleware) // Runs SECOND (skips OPTIONS) ```

  1. 1.Implement conditional auth middleware that skips OPTIONS:
  2. 2.```rust
  3. 3.use actix_web::dev::{ServiceRequest, ServiceResponse, Transform, Service};
  4. 4.use actix_web::Error;
  5. 5.use std::future::{ready, Ready, ready as future_ready};
  6. 6.use std::pin::Pin;
  7. 7.use std::task::{Context, Poll};

pub struct AuthMiddleware;

impl<S, B> Transform<S, ServiceRequest> for AuthMiddleware where S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static, S::Future: 'static, { type Response = ServiceResponse<B>; type Error = Error; type Transform = AuthMiddlewareService<S>; type InitError = (); type Future = Ready<Result<Self::Transform, Self::InitError>>;

fn new_transform(&self, service: S) -> Self::Future { ready(Ok(AuthMiddlewareService { service })) } }

pub struct AuthMiddlewareService<S> { service: S, }

impl<S, B> Service<ServiceRequest> for AuthMiddlewareService<S> where S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static, S::Future: 'static, { type Response = ServiceResponse<B>; type Error = Error; type Future = Pin<Box<dyn std::future::Future<Output = Result<Self::Response, Self::Error>>>>;

fn poll_ready(&self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { self.service.poll_ready(cx) }

fn call(&self, req: ServiceRequest) -> Self::Future { // Skip auth for OPTIONS (CORS preflight) if req.method() == "OPTIONS" { return Box::pin(self.service.call(req)); }

// Check authorization header let auth_header = req.headers().get("Authorization"); if auth_header.is_none() || !validate_token(auth_header.unwrap()) { return Box::pin(async { Err(actix_web::error::ErrorUnauthorized("Invalid token")) }); }

Box::pin(self.service.call(req)) } } ```

Prevention

  • Document middleware order in project README with a diagram
  • Add a test that verifies OPTIONS requests are not rejected by auth
  • Use middleware::Logger as the outermost wrap to capture full lifecycle
  • Write custom middleware that logs entry and exit order during development
  • Remember: request = reverse order, response = forward order
  • Keep middleware chain short (5 or fewer) for performance