Understanding Tower
Tower provides three core abstractions:- Service: An asynchronous function from a request to a response
- Layer: Middleware that wraps a service to modify its behavior
- ServiceBuilder: A utility for composing layers
Axum’s
Router implements tower::Service, so it works seamlessly with all Tower middleware.Adding middleware with layers
Use the.layer() method to add Tower middleware:
Middleware execution order
Middleware executes in reverse order of how it’s added:- Request → TraceLayer → CorsLayer → CompressionLayer → Handler
- Handler → CompressionLayer → CorsLayer → TraceLayer → Response
tower-http middleware
Thetower-http crate provides HTTP-specific middleware:
CORS
Handle Cross-Origin Resource Sharing:Advanced CORS configuration
Advanced CORS configuration
Compression
Compress response bodies:Tracing and logging
Log requests and responses:Request timeouts
Set timeouts for requests:Request/response size limits
Static file serving
Serve static files:ServiceBuilder for composing middleware
UseServiceBuilder to organize multiple layers:
ServiceBuilder applies layers in the order they appear (unlike .layer() which applies them in reverse).