Middleware: The Tower Ecosystem
6 min read
Module 6: Middleware & The Tower Ecosystem 🗼
Welcome back, fellow Rustacean! 🦀
You’ve built routes, you’ve handled JSON, and you’ve probably panicked at least once about the borrow checker today. Now it's time to level up.
We are entering the world of Middleware.
If you think "Middleware" sounds like "software that sits in the middle," you are technically correct (the best kind of correct). But in the Rust ecosystem, specifically with Axum, middleware is powered by a library called Tower.
Understanding Tower is like learning the Force in the Star Wars universe. It binds the galaxy (your web stack) together.
1. Enter Tower: Understanding the Service Abstraction
Definition & The Problem
Imagine you are building a web server. You need to handle logging, timeouts, authentication, and compression for every single route.
- The Problem: If you write this logic inside every handler function, your code becomes a messy spaghetti monster. 🍝
- The Solution: You need a standard interface that says, "I take a request, I process it (or fail), and I return a response."
Tower provides this standard. It defines a trait called Service.
The Concept
In the Tower ecosystem (and thus Axum), everything is a Service.
- Your Axum
Router? It's a Service. - Your handler function? It gets turned into a Service.
- A Timeout layer? It's a Service that wraps another Service.
This creates an "onion" architecture.
The Flow:Request ➡️ [Middleware A] ➡️ [Middleware B] ➡️ [Your Handler] ➡️ [Response]
Industry Fact: Tower is not just for HTTP. It is protocol agnostic. The same library handles retry logic for database connections or gRPC calls!
2. Built-in Middleware: CORS, Timeout, and Payload Limits
You don't need to reinvent the wheel. The crate tower-http contains the "batteries-included" middleware used by 99% of production Rust servers.
First, let's get our dependencies right. Open Cargo.toml:
[dependencies]
axum = "0.7"
tokio = { version = "1", features = ["full"] }
# We need specific features from tower-http
tower-http = { version = "0.5", features = ["cors", "timeout", "limit", "trace"] }
tracing = "0.1"
tracing-subscriber = "0.3"A. CORS (Cross-Origin Resource Sharing)
- Problem: You built a beautiful API. Your frontend developer (React/Vue/Svelte) tries to
fetch()data from it. The browser screams: 🔴 CORS ERROR. This is a security feature preventing unauthorized websites from reading your API. - Solution: The
CorsLayer.
use axum::{routing::get, Router};
use tower_http::cors::{CorsLayer, Any};
use std::time::Duration;
#[tokio::main]
async fn main() {
// ⚠️ Security Warning: In production, do not use `Any`.
// Specify your actual frontend domain like "https://myapp.com".
let cors = CorsLayer::new()
.allow_origin(Any)
.allow_methods(Any)
.allow_headers(Any);
let app = Router::new()
.route("/", get(|| async { "Hello, World!" }))
.layer(cors); // <--- We wrap the router with CORS
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
}B. Timeouts
- Problem: A user sends a request. Your database locks up. The user's browser spins forever. Your server resources are held hostage.
- Solution:
TimeoutLayer. If the handler takes too long, kill it.
C. Payload Limits
- Problem: A malicious actor sends a 50GB JSON file to your login endpoint. Your server runs out of RAM and crashes (DoS attack).
- Solution:
DefaultBodyLimit.
Combining Them (The Production Stack)
Here is how you actually write this in a real job:
use axum::{Router, http::Method};
use tower_http::{
cors::{CorsLayer, Any},
timeout::TimeoutLayer,
limit::RequestBodyLimitLayer,
};
use std::time::Duration;
// ... inside main ...
let app = Router::new()
.route("/", get(handler))
// 1. Limit body size to 10MB (Order matters!)
.layer(RequestBodyLimitLayer::new(10 * 1024 * 1024))
// 2. Timeout after 10 seconds
.layer(TimeoutLayer::new(Duration::from_secs(10)))
// 3. Allow CORS
.layer(CorsLayer::new().allow_methods([Method::GET, Method::POST]));⚠️ Important Order of Operations:
Middleware layers wrap from bottom to top (when using.layer()).
However, they execute from outside in.
In the code above, the request hits CORS first, then Timeout, then Limit.
3. Tracing & Logging: Setting up tower-http for Request Logs
- Problem: Your server returns a
500 Internal Server Error. You stare at the console. It is blank. You have no idea what happened. - Solution: Structured Logging with
tracingandTraceLayer.
Do not use println! in production. println! is blocking and unstructured. Use tracing.
Step 1: Initialize the Subscriber
You need to turn the lights on before you can see.
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
#[tokio::main]
async fn main() {
// Initialize tracing
tracing_subscriber::registry()
.with(tracing_subscriber::fmt::layer())
.init();
// ... app setup
}Step 2: Add the Middleware
Now, tell Axum to log every HTTP request.
use tower_http::trace::TraceLayer;
let app = Router::new()
.route("/", get(|| async {
// You can log inside handlers too!
tracing::info!("Inside the handler!");
"Hello"
}))
.layer(TraceLayer::new_for_http());What you see in the terminal:
2023-10-27T10:00:00Z INFO request{method=GET path=/}: axum_app: started processing request
2023-10-27T10:00:00Z INFO axum_app: Inside the handler!
2023-10-27T10:00:00Z INFO request{method=GET path=/ status=200}: axum_app: finished processing request latency=0 msFun Fact: If you deploy to AWS or Google Cloud, they automatically ingest these logs. If you use
println!, it often gets lost or formatted poorly. Structured logging is key to keeping your job. 💼
4. Writing Custom Middleware: Intercepting Requests
Sometimes, the built-in tools aren't enough. You need to check a custom header, measure specific metrics, or simply annoy your users by injecting a random delay.
In the old days, implementing Service manually was hard (lots of boilerplate).
Axum 0.6+ gave us axum::middleware::from_fn. It's magical. 🪄
The Pattern
An Axum middleware function looks like a handler, but it takes an extra argument: Next.
use axum::{
middleware::{self, Next},
response::Response,
extract::Request,
routing::get,
Router,
};
// 1. Define the middleware function
async fn my_custom_middleware(
request: Request, // The incoming request
next: Next, // The rest of the middleware chain/handler
) -> Response {
// --- Logic BEFORE the handler ---
println!("Received a request to: {}", request.uri());
// Check a custom header (e.g., a secret API key)
let has_secret = request.headers().contains_key("x-secret-sauce");
if !has_secret {
// We can reject the request here! The handler is never called.
// We return a Response immediately.
return "You forgot the sauce!".into_response();
}
// --- Call the next middleware/handler ---
let response = next.run(request).await;
// --- Logic AFTER the handler ---
println!("Handler finished. Status: {}", response.status());
response
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(|| async { "Yum, tasty sauce!" }))
.layer(middleware::from_fn(my_custom_middleware)); // <--- Apply it here
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
}Real World Use Case: Authentication Guards
While Axum has Extractors for data, Middleware is great for "Guards" — stopping a request at the door if it doesn't meet criteria (like a missing token).
Summary of Flows
- Request enters ➡️
my_custom_middlewarestarts. - Pre-logic runs (Header check).
- Next:
next.run(req).awaitcalls the actual route handler. - Handler returns a response.
- Post-logic runs (Logging status).
- Response exits ⬅️.
🏁 Conclusion
You now possess the power of the Tower.
- Service Trait: The universal language of Rust async requests.
- tower-http: Your toolbox for CORS, Timeout, and Limits.
- Tracing: Your eyes in the dark.
- Custom Middleware: Your ability to intercept and modify traffic.
📚 References & Further Reading
- Axum Middleware Documentation - The official guide.
- Tower HTTP Docs - List of all built-in middleware.
- Tracing Crate - Deep dive into logging.
- Tower Service Trait - For the brave souls who want to see the underlying definition.
Now go forth and layer() your routers! 🛡️
Challenge
You are given a complex JSON object representing a user's profile. Your task is to write a JavaScript function named processUserProfile that accepts this user object as its only argument.
The function must perform the following operations:
- Construct the user's full name by combining the
firstNameandlastNameproperties, separated by a space. - Iterate through the
contactInfo.emailsarray to find the email address that is marked as primary (where theprimaryproperty istrue). - Go through all the objects in the
postsarray. For each post, collect all the strings from itstagsarray. You must compile a list of all unique tags from all posts, without any duplicates. The order of tags in the final list does not matter.
Finally, the function should return a new object with the following structure:
{
"fullName": "...",
"primaryEmail": "...",
"allUniqueTags": [...]
}Expected result
The processUserProfile function, when implemented correctly and called with the provided userProfile object, should return a new object. This returned object must have three specific keys:
fullName: A string containing"Alex Johnson".primaryEmail: A string containing"[email protected]".allUniqueTags: An array of strings containing all unique tags from the posts. The expected tags are:"javascript","es6","async","css","frontend","layout", and"design-patterns". The order of elements in this array does not matter.