Chapter 11: Middleware Basics in Rust

What middleware is and why it matters. In this chapter, you will learn middleware basics in depth with Rust code examples, explanations, and best practices.

Overview

This chapter covers middleware basics for Kungfu.js developers using Rust. We will start with the basics, move through practical examples, and end with advanced techniques and common pitfalls.

Why This Matters

Understanding middleware basics is essential because it is a core part of building web applications. Every real-world app needs to handle what middleware is and why it matters. Skipping this chapter would leave a gap in your knowledge that would cause problems later.

Code Example

Here is how to use middleware in Rust:

use std::sync::Arc;

let add_request_id = Arc::new(|req, next| {
    Box::pin(async move {
        let id = req.header("x-request-id")
            .map(|s| s.to_string())
            .unwrap_or_else(|| "unknown".to_string());
        let mut resp = next(req).await;
        resp.set_header("x-request-id", id);
        resp
    })
});

// Auth middleware (short-circuits if no API key)
let require_auth = Arc::new(|req, next| {
    Box::pin(async move {
        if req.header("x-api-key").is_none() {
            return Response::new().status(StatusCode::Unauthorized)
                .text("Missing API key");
        }
        next(req).await
    })
});

Kungfu::new()
    .use_middleware(add_request_id)  // runs first
    .use_middleware(require_auth)    // runs second
    .handle_get("/data", |_req, res| res.text("secret data"))

The Onion Model

Middleware in Kungfu.js uses the "onion" model. Imagine an onion with layers. A request passes through each layer from outside to inside, then the response passes back through the same layers from inside to outside.

This means the first middleware you register runs first on the request (before the handler) and last on the response (after the handler). The last middleware runs last on the request and first on the response.

Common Mistakes

  • Not reading the documentation: Always check the API reference when something does not work as expected.
  • Skipping security: Never disable the default middleware unless you have a very good reason. Security is not optional.
  • Not testing: Write tests for your handlers. Kungfu.js makes this easy with the built-in test utilities.

Summary

In this chapter, you learned about middleware basics in Rust. You saw code examples, understood how things work under the hood, and learned about common mistakes to avoid.

What is Next?

In chapter 12, we will cover Built-in Middleware: Security headers, CORS, rate limiting, logging.