Actix-web vs Axum middleware compatibility
Understand how middleware works in Axum and Actix-web, why they use different systems, and what that means for reusing code between the two frameworks.
A web framework does more than just route requests to handlers. Before a request reaches your function, you often want to log it, check authentication, compress the response, or add security headers. The code that sits in front of your handler and does that work is called middleware. Every modern web framework has a way to plug in such code, and both Axum and Actix-web are no exception.
The catch: Axum and Actix-web implement middleware using completely different internal systems. Axum is built on the Tower middleware ecosystem, which is generic and shared across many Rust libraries. Actix-web has its own middleware system, designed specifically for Actix. That means a middleware written for Actix cannot be dropped into an Axum application, and a Tower middleware cannot be used directly in Actix. But the concepts are almost identical, and porting logic from one to the other is straightforward once you understand the patterns.
This page focuses on that compatibility story. You'll learn what middleware is in simple terms, how each framework attaches it, what "compatibility" really means here, and how to translate a middleware from one system to the other. You'll write real code for both frameworks and see the differences side by side.
Prerequisite knowledge:
This page assumes you have seen the basics of Axum and Actix-web routing, and that you know what an HTTP request and response are. A handler is the function that answers a request, and a Router is the object that maps paths and methods to handlers. Both terms are defined as they appear on this page.
What middleware does in a web request
Imagine a request arriving at your server. It goes through several stages:
Client sends request
↓
Middleware (before handler)
↓
Your handler function
↓
Middleware (after handler)
↓
Client receives response
Middleware can inspect or modify the request before it reaches your handler. It can also inspect or modify the response before it goes back to the client. Some middleware only runs "before" (for example, an authentication check that rejects invalid requests). Some only runs "after" (for example, compressing the response body). Most do both.
Common examples of middleware:
- Logging - record information about every request.
- Compression - shrink large responses before sending.
- CORS headers - tell browsers which websites are allowed to call your API.
- Authentication - reject requests without a valid token.
- Rate limiting - stop one client from making too many requests.
- Request ID injection - add a unique ID to each request for tracing.
Without middleware, you would need to copy-paste this logic into every handler. Middleware keeps that logic in one place and applies it to many routes at once.
How Axum attaches middleware through Tower
Axum does not invent its own middleware system. Instead, it reuses Tower, a separate Rust library that provides a standard way to build and compose services. Tower defines two core ideas:
- A Service is something that takes a request and returns a future that resolves to a response. Your Axum
Routeris a Service. - A Layer wraps a Service and returns a new Service, usually with extra behavior. That extra behavior is the middleware.
When you write Router::new().layer(...), you are putting a Layer on top of the Router. The Layer changes the Router into a new Service that runs the middleware code before and after the original Router handles the request.
Tower is not part of Axum; it's a standalone library maintained by the same team that maintains Tokio. Because so many Rust libraries use Tower, you can use almost any Tower-compatible middleware with Axum. The tower-http crate is a collection of ready-made Layers for HTTP-specific tasks: CORS, compression, tracing, request ID, and more.
A minimal Axum middleware example
Let's create a simple Axum server that uses two Tower middlewares: request logging and CORS.
First, add the dependencies to Cargo.toml:
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
tower-http = { version = "0.7", features = ["trace", "cors"] }
tracing = "0.1"
tracing-subscriber = "0.3"
Now write src/main.rs:
use axum::{
routing::get,
Router,
};
use tower_http::{
cors::{Any, CorsLayer},
trace::{DefaultMakeSpan, DefaultOnRequest, DefaultOnResponse, TraceLayer},
};
use tracing::Level;
#[tokio::main]
async fn main() {
// Initialize logging so TraceLayer can output request logs.
tracing_subscriber::fmt::init();
// A basic CORS layer that allows any origin, method, and header.
let cors = CorsLayer::new()
.allow_origin(Any)
.allow_methods(Any)
.allow_headers(Any);
let app = Router::new()
.route("/", get(|| async { "Hello from Axum!" }))
.layer(cors)
.layer(
TraceLayer::new_for_http()
.make_span_with(DefaultMakeSpan::new().level(Level::INFO))
.on_request(DefaultOnRequest::new().level(Level::INFO))
.on_response(DefaultOnResponse::new().level(Level::INFO)),
);
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
println!("Listening on http://localhost:3000");
axum::serve(listener, app).await.unwrap();
}
When you run this and visit http://localhost:3000, you'll see the handler's response. In the terminal, TraceLayer prints a log line for the request. The CorsLayer adds CORS headers to the response, which you can verify by opening your browser's developer tools and looking at the response headers.
The explicit .level(Level::INFO) calls matter. By default, TraceLayer logs its request and response events at DEBUG level, and tracing_subscriber::fmt::init() only shows events at INFO and above - so with a plain TraceLayer::new_for_http() you would see nothing in the terminal. Setting the level to INFO makes the lines appear.
What happened mechanically: Router::new() created a Service. .layer(cors) wrapped that Service with a new Service that adds CORS handling. .layer(...) with the configured TraceLayer wrapped the result again with another Service that logs. The final Service is passed to axum::serve. When a request arrives, it flows through the Trace middleware first (logs start), then through the CORS middleware, then into the Router and your handler. The response flows back out through the same layers in reverse.
Everything works when you see this:
If your terminal prints lines like INFO tower_http::trace::on_request: started processing request and your browser shows access-control-allow-origin: * in the response headers, both middlewares are active. You have successfully attached Tower Layers to an Axum Router.
How Actix-web attaches middleware
Actix-web has its own middleware system. Instead of Tower's Layer and Service, Actix defines a Transform trait and a matching Service trait in the actix_web::dev module. Conceptually they work the same: a Transform takes a Service and returns a new Service with extra behavior.
Actix-web ships with several built-in middlewares in the actix_web::middleware module: Logger, Compress, DefaultHeaders, NormalizePath, and others. You attach them with .wrap() on an App.
A minimal Actix-web middleware example
Here's the equivalent of the previous Axum example, but using Actix-web's built-in logger.
Add dependencies to Cargo.toml:
[dependencies]
actix-web = "4"
env_logger = "0.11"
log = "0.4"
Write src/main.rs:
use actix_web::{middleware::Logger, web, App, HttpServer, Responder};
async fn index() -> impl Responder {
"Hello from Actix-web!"
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
// Initialize logging so the Logger middleware can write to stdout.
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
HttpServer::new(|| {
App::new()
.wrap(Logger::default())
.route("/", web::get().to(index))
})
.bind("0.0.0.0:3000")?
.run()
.await
}
Run this and visit the same URL. The terminal will show request logs similar to [2026-08-30T12:00:00Z INFO actix_web::middleware::logger] 127.0.0.1 "GET / HTTP/1.1" 200 20 "-" "curl/8.0.1". The response body is your text.
Mechanically, .wrap(Logger::default()) wraps the App's default service with Actix's Logger middleware. When a request comes in, Logger records the start time and request details, then calls the inner service, then records the response status and duration.
Comparing the two middleware models side by side
At a high level, both systems do the same thing: they let you insert code before and after the handler. But the underlying traits and types are different.
| Aspect | Axum / Tower | Actix-web |
|---|---|---|
| Core abstraction | tower::Layer (constructor) and tower::Service (runtime) | actix_web::dev::Transform (constructor) and actix_web::dev::Service (runtime) |
| How you attach | .layer(...) on Router | .wrap(...) on App |
| Standard middleware crate | tower-http (plus many third-party Tower crates) | actix-web::middleware (built-in) and community crates |
| Generality | Tower is used by Hyper, Tonic, and many other tools | Actix middleware is tied to Actix's own types |
The most important difference: Tower is a shared, framework-agnostic middleware ecosystem. If you learn how to write a Tower Layer, you can use it with Axum, with Hyper directly, with Tonic (a gRPC framework), or any other Tower-based service. Actix-web's middleware is only usable inside Actix-web.
That does not mean Actix-web is worse - it just means its middleware is purpose-built. Actix has many production-ready middlewares that are very easy to use because they assume Actix's request and response types.
What "middleware compatibility" actually means
When people ask about middleware compatibility between Actix-web and Axum, they usually mean one of two things:
- "Can I use an Actix middleware in an Axum app?" No. An Actix middleware implements Actix's
TransformandServicetraits, which expect Actix-specific request and response types (actix_web::dev::ServiceRequest,ServiceResponse, etc.). Axum's Router is a TowerServicethat works withhttp::Requestandhttp::Response. The types don't line up, so the compiler will reject any attempt to mix them. - "Can I achieve the same functionality in both frameworks?" Yes. Almost every Actix middleware has a counterpart in the Tower ecosystem, and vice versa. You just need to know which crate provides it.
Common middleware equivalents
Here are some popular middlewares and how you would get the same behavior in each framework:
| Functionality | Actix-web | Axum / Tower |
|---|---|---|
| Request logging | actix_web::middleware::Logger | tower_http::trace::TraceLayer |
| Response compression | actix_web::middleware::Compress | tower_http::compression::CompressionLayer |
| CORS | actix-cors crate | tower_http::cors::CorsLayer |
| Default headers | actix_web::middleware::DefaultHeaders | tower_http::set_header::SetResponseHeaderLayer |
| Request ID | No built-in middleware - use a community crate or a small custom Transform (there is no actix_web::middleware::RequestId) | tower_http::request_id::SetRequestIdLayer (with PropagateRequestIdLayer to copy it to the response) |
| Rate limiting | actix_web_ratelimit crate | tower::limit::RateLimitLayer - note the crate is tower, not tower-http (tower_http::limit only has RequestBodyLimitLayer, which caps body size with a 413) |
| Timeouts | No built-in middleware - timeouts come from the server/worker configuration or a custom Transform (there is no actix_web::middleware::Timeout) | tower_http::timeout::TimeoutLayer, which answers with a status code instead of an error. The plain tower::timeout::TimeoutLayer does not work on a Router on its own - it needs a HandleErrorLayer to convert its error into a response |
Note that some functionality may not have a ready-made Layer in tower-http, but you can always write your own using Tower's traits - or find a third-party Tower crate.
The real compatibility story:
tower-http layers work with anything built on Tower's Service - Axum, tonic (gRPC), and raw Hyper services - but not with Actix-web, because Actix-web's middleware uses its own actix-service Transform/Service traits. Conversely, Actix-web's built-in middleware (Logger, Compress, DefaultHeaders, NormalizePath, ErrorHandlers, Condition, TrailingSlash) only works inside Actix-web. There is no adapter that makes one side's middleware run in the other framework; you port the logic, not the type.
Porting a simple middleware from Actix to Axum
Let's take a concrete example: a logging middleware that records the method and path of each request. We'll implement it in Actix first, then port it to Axum using Tower. This will show you exactly how the patterns map.
Actix-web custom middleware
Actix custom middleware requires implementing Transform and Service. The Transform creates a new instance of the middleware service for each worker thread. The Service implements call, which receives a ServiceRequest, does something, calls the next service, and returns a ServiceResponse.
Here's a complete Actix program with a custom middleware that prints the method and path:
use actix_web::{
dev::{forward_ready, Service, ServiceRequest, ServiceResponse, Transform},
web, App, Error, HttpServer,
};
use std::future::{ready, Future, Ready};
use std::pin::Pin;
pub struct LogMethodPath;
impl<S, B> Transform<S, ServiceRequest> for LogMethodPath
where
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
S::Future: 'static,
B: 'static,
{
type Response = ServiceResponse<B>;
type Error = Error;
type Transform = LogMethodPathMiddleware<S>;
type InitError = ();
type Future = Ready<Result<Self::Transform, Self::InitError>>;
fn new_transform(&self, service: S) -> Self::Future {
ready(Ok(LogMethodPathMiddleware { service }))
}
}
pub struct LogMethodPathMiddleware<S> {
service: S,
}
impl<S, B> Service<ServiceRequest> for LogMethodPathMiddleware<S>
where
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
S::Future: 'static,
B: 'static,
{
type Response = ServiceResponse<B>;
type Error = Error;
type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>>>>;
forward_ready!(service);
fn call(&self, req: ServiceRequest) -> Self::Future {
println!("Request: {} {}", req.method(), req.path());
let fut = self.service.call(req);
Box::pin(async move {
let res = fut.await?;
println!("Response status: {}", res.status());
Ok(res)
})
}
}
async fn index() -> &'static str {
"Hello"
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
.wrap(LogMethodPath)
.route("/", web::get().to(index))
})
.bind("127.0.0.1:3000")?
.run()
.await
}
This is a lot of boilerplate for such a simple task. That's Actix's cost for being very explicit about types. The important parts: Transform::new_transform returns a new Service that wraps the inner service. The new Service's call method runs code, calls the inner service, and optionally runs code after.
Axum / Tower custom middleware
In Tower, a middleware is usually a Layer that produces a Service. The Layer implements tower::Layer<Inner>, and the produced Service implements tower::Service<Request>. Because Tower's Service trait has an associated Future type, writing middleware can be simpler with helper crates like tower::util::ServiceExt, but here we'll do it manually.
First, add tower to Cargo.toml:
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
tower = "0.5"
Now the Axum version:
use axum::{body::Body, http::{Request, Response}, routing::get, Router};
use std::{
convert::Infallible,
future::Future,
pin::Pin,
task::{Context, Poll},
};
use tower::{Layer, Service};
#[derive(Clone)]
pub struct LogMethodPathLayer;
impl<S> Layer<S> for LogMethodPathLayer {
type Service = LogMethodPathService<S>;
fn layer(&self, inner: S) -> Self::Service {
LogMethodPathService { inner }
}
}
#[derive(Clone)]
pub struct LogMethodPathService<S> {
inner: S,
}
impl<S> Service<Request<Body>> for LogMethodPathService<S>
where
S: Service<Request<Body>, Response = Response<Body>, Error = Infallible> + Clone + Send + 'static,
S::Future: Send + 'static,
{
type Response = Response<Body>;
type Error = Infallible;
type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.inner.poll_ready(cx)
}
fn call(&mut self, req: Request<Body>) -> Self::Future {
let method = req.method().clone();
let path = req.uri().path().to_owned();
println!("Request: {method} {path}");
let future = self.inner.call(req);
Box::pin(async move {
let res = future.await?;
println!("Response status: {}", res.status());
Ok(res)
})
}
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(|| async { "Hello" }))
.layer(LogMethodPathLayer);
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
println!("Listening on http://localhost:3000");
axum::serve(listener, app).await.unwrap();
}
The key difference from a generic Tower service is the constraint on the Service implementation: Service<Request<Body>> instead of Service<Req>. Axum handlers work with http::Request<axum::body::Body>, so pinning the request type to that is what lets call read req.method() and req.uri().path() before passing the request on. The method and path are copied out of the request first, because call moves the request into the inner service and the log line after the response needs them. Run it and visit /: the terminal prints Request: GET / followed by Response status: 200 OK.
The Axum version is also quite verbose, and this constraint is exactly why: a Tower service that works for any request type cannot read HTTP details, so you give up some of that generality the moment you want method and path. In practice, you rarely write raw Tower services like this; the usual first choice is axum::middleware::from_fn, which lets you write the same logic as a plain async function, and for logging specifically tower_http::trace::TraceLayer already does this job. This example shows the core pattern underneath both.
Why Axum's middleware is more reusable
When you write a Tower middleware, you aren't writing it for Axum specifically. You are writing it for any Service that accepts the request type you specify. If you write a middleware that adds a header to every response, it will work with Axum, with Hyper, with a Tonic gRPC server, or even with a custom TCP service. That means the ecosystem of reusable middleware is enormous. Crates like tower, tower-http, tower-sessions, tower-livereload, and countless others all work out of the box with Axum.
Actix-web's middleware is tied to Actix's own ServiceRequest and ServiceResponse. That allows Actix to provide very ergonomic middleware APIs because they know exactly what a request looks like. For example, Actix's Logger middleware can format logs using named fields like %a, %r, %s - a familiar syntax from Apache logs - without any extra configuration. But that specificity means you cannot use the same middleware outside Actix.
Trade-off isn't about quality:
Neither approach is inherently better. Actix's middleware is easier to use within Actix, while Tower's middleware is more portable but sometimes requires more boilerplate for HTTP-specific features. Many teams choose Axum precisely because they want to share middleware across services that use Tower.
Common mistakes and how to avoid them
Beginners often run into a few predictable problems when dealing with middleware in these two frameworks.
Mistake 1: Trying to use Actix middleware in an Axum app
You might see a crate like actix-cors and assume it will work with Axum. It will not. actix-cors expects an actix_web::dev::ServiceRequest, and Axum sends a http::Request<axum::body::Body>. The compiler will produce a long error about mismatched types. The fix is to use the Tower equivalent: tower_http::cors::CorsLayer.
Compiler errors when mixing ecosystems:
If you attempt to apply an Actix middleware to an Axum Router, you will see a compile error similar to "the trait bound actix_web::dev::ServiceRequest is not satisfied". This is not a bug; it's Rust's type system correctly preventing you from combining incompatible types. Always use middleware from the matching ecosystem.
Mistake 2: Assuming .layer() and .wrap() are interchangeable
In Axum, you call .layer() on a Router. In Actix, you call .wrap() on an App. The order of multiple .layer() calls matters: the last layer you add is the first to see the request. In Actix, the same is true for .wrap(): the last wrap runs first. It's easy to get the order backwards and end up with middleware not seeing what you expect.
Mistake 3: Not realizing middleware runs for every request, including 404s
Both frameworks run middleware before routing happens. So a logging middleware will log requests even for paths that don't exist. If you want to restrict middleware to certain routes, you need to use route-specific middleware (Axum supports .route_layer on individual routes, and Actix has web::scope with its own wraps).
Mistake 4: Forgetting to clone state or services in middleware
When writing custom middleware, the Service is created once and cloned for each request. If your middleware holds state that needs to be shared, you must wrap it in an Arc or use #[derive(Clone)] correctly. This is true in both frameworks and a frequent source of confusing ownership errors.
Middleware services must be clonable:
Both Tower and Actix require the middleware service to be clonable because the runtime may create multiple copies for concurrent requests. If your service contains a non-clonable type, the compiler will complain. Wrap shared data in Arc and derive Clone.
Choosing between the two middleware ecosystems
If you are building a new application and must decide between Axum and Actix-web based on middleware, consider these points:
- If you already use other Tower-based tools (like Tonic for gRPC or Hyper directly), Axum lets you reuse your middleware across all of them. That consistency can reduce duplicated logic.
- If you prefer batteries-included middleware with simple configuration and you don't need cross-framework reuse, Actix-web's built-in set is excellent. Its
LoggerandCompressare very easy to enable. - The
tower-httpcrate is actively maintained and has a wide variety of HTTP-specific middlewares. Actix's built-in set is smaller, but many additional middlewares are available as community crates.
Neither choice locks you in forever - you can port middleware between them with some effort, as we demonstrated.
A practical porting checklist
When you need to move a piece of middleware from Actix-web to Axum (or vice versa), use this workflow:
- Identify the middleware's purpose: does it inspect the request, modify the response, or both?
- Find the equivalent off-the-shelf middleware in the target ecosystem. Check
tower-httpfor Axum, andactix-web::middlewareplus community crates for Actix. - If no equivalent exists, plan to write a custom middleware. For Axum, implement a
tower::Layerandtower::Service. For Actix, implementTransformandServicefromactix_web::dev. - Translate the logic carefully, keeping in mind the different request and response types.
- Test the middleware in isolation with a simple route before applying it broadly.
This checklist works for almost any middleware.
Summary
Middleware compatibility between Actix-web and Axum is not about being able to drop one framework's middleware into the other. It's about understanding that both frameworks provide the same concept - code that wraps your handlers - but implement it with different internal abstractions. Axum uses Tower's Layer and Service, which are shared across the Rust async ecosystem. Actix uses its own Transform and Service types, which are specific to Actix but often easier to use within that framework.
The practical implication is that you choose a middleware library based on which framework you're using. If you're on Axum, look to tower-http and the broader Tower ecosystem. If you're on Actix, look to actix-web::middleware and Actix-specific crates. The patterns you learn in one system transfer to the other, and porting a middleware is mostly a matter of translating types and method names.
The biggest takeaway: Axum's middleware model is not an Axum invention - it's a shared standard. That is both its strength and the reason you cannot directly reuse Actix middleware. Once you understand Tower's Layer and Service, you've learned something that goes far beyond Axum.