0Pricing
Learn Rust Coding · Lesson

Middleware

Tower layers.

Middleware is a free Learn Rust Coding lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Learn Rust Coding learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

What is middleware?

Middleware runs code before and after a handler, wrapping the request/response cycle. Use it for logging, auth, compression, and timeouts.

  • Axum builds on the tower ecosystem
  • Middleware is added as layers

The Service trait

Tower defines a Service: something that takes a request and asynchronously produces a response. Layers wrap one service in another.

Adding a layer

Attach middleware with .layer(). Here we add request tracing from tower_http.

use axum::{Router, routing::get};
use tower_http::trace::TraceLayer;

fn app() -> Router {
    Router::new()
        .route("/", get(|| async { "ok" }))
        .layer(TraceLayer::new_for_http())
}

Layer ordering

Layers wrap from the bottom up: the last layer added is the outermost. Requests flow outer to inner, responses inner to outer.

use axum::{Router, routing::get};
use tower_http::{trace::TraceLayer, compression::CompressionLayer};

fn app() -> Router {
    Router::new()
        .route("/", get(|| async { "ok" }))
        .layer(CompressionLayer::new())
        .layer(TraceLayer::new_for_http())
}

Custom middleware with from_fn

middleware::from_fn turns an async function into middleware. It receives the request and a Next to call the rest of the chain.

use axum::{middleware::Next, response::Response, extract::Request};

async fn log_mw(req: Request, next: Next) -> Response {
    println!("{} {}", req.method(), req.uri());
    next.run(req).await
}

Wiring custom middleware

Wrap your function with from_fn and add it as a layer.

use axum::{Router, routing::get, middleware};

fn app() -> Router {
    Router::new()
        .route("/", get(|| async { "ok" }))
        .layer(middleware::from_fn(log_mw))
}

Short-circuiting requests

Middleware can return early without calling next, useful for auth. Returning a response stops the chain.

use axum::{middleware::Next, response::Response, extract::Request, http::StatusCode};

async fn auth(req: Request, next: Next) -> Result<Response, StatusCode> {
    if req.headers().contains_key("authorization") {
        Ok(next.run(req).await)
    } else {
        Err(StatusCode::UNAUTHORIZED)
    }
}

Modeling a middleware chain

A chain is just functions calling the next one. This runnable example models the before/after wrapping.

fn handler() -> String {
    "response".to_string()
}

fn logging<F: Fn() -> String>(next: F) -> String {
    println!("-> request in");
    let res = next();
    println!("<- response out");
    res
}

fn main() {
    let out = logging(handler);
    println!("body: {}", out);
}

Per-route middleware

Apply a layer to a single route by calling .layer() on the method router instead of the whole app.

use axum::{Router, routing::get, middleware};

fn app() -> Router {
    Router::new().route(
        "/admin",
        get(|| async { "admin" }).layer(middleware::from_fn(auth)),
    )
}

Common tower_http layers

The tower_http crate ships ready-made middleware:

  • TraceLayer for logging
  • CompressionLayer for gzip
  • CorsLayer for CORS
  • TimeoutLayer to bound request time
use tower_http::cors::CorsLayer;

fn cors() -> CorsLayer {
    CorsLayer::permissive()
}

Stacking with ServiceBuilder

Group multiple layers cleanly with ServiceBuilder, which applies them top to bottom for predictable ordering.

use tower::ServiceBuilder;
use tower_http::{trace::TraceLayer, compression::CompressionLayer};

fn stack() -> ServiceBuilder<impl Sized> {
    ServiceBuilder::new()
        .layer(TraceLayer::new_for_http())
        .layer(CompressionLayer::new())
}

Quick Check

Test your understanding of middleware.

Recap

You learned middleware with tower layers:

  • Add middleware via .layer(); last added is outermost
  • from_fn builds custom middleware using Next
  • Return early to short-circuit, e.g. for auth
  • tower_http offers trace, compression, CORS, and timeout layers

That completes the Axum course.

Frequently asked questions

Is the “Middleware” lesson free?

Yes — the full text of “Middleware” is free to read here on the web, and the Learn Rust Coding course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Learn Rust Coding course, upgrade to CoddyKit PRO.

What will I learn in “Middleware”?

Tower layers. You practise Learn Rust Coding with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Learn Rust Coding?

No prior experience is required. Learn Rust Coding on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Middleware” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Learn Rust Coding lesson?

Yes. Every Learn Rust Coding lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Axum Routing
  2. Extractors
  3. JSON and State
  4. Middleware
← Back to Learn Rust Coding