Skip to main content
Kit provides a powerful middleware system for intercepting and processing HTTP requests before they reach your route handlers. Middleware can inspect, modify, or short-circuit requests, and also post-process responses.

Generating Middleware

The fastest way to create a new middleware is using the Kit CLI:
This command will:
  1. Create src/middleware/auth.rs with a middleware stub
  2. Update src/middleware/mod.rs to export the new middleware

Overview

Middleware sits between the incoming request and your route handlers, allowing you to:
  • Authenticate and authorize requests
  • Log requests and responses
  • Add CORS headers
  • Rate limit requests
  • Transform request/response data
  • And much more

Creating Middleware

To create middleware, define a struct and implement the Middleware trait:

The handle Method

The handle method receives:
  • request: The incoming HTTP request
  • next: A function to call the next middleware in the chain (or the route handler)
You can:
  • Continue the chain: Call next(request).await to pass control to the next middleware
  • Short-circuit: Return a response early without calling next()
  • Modify the request: Transform the request before calling next()
  • Modify the response: Transform the response after calling next()

Short-Circuiting Requests

Return early to block a request from reaching the route handler:

Registering Middleware

Kit supports three levels of middleware:

1. Global Middleware

Global middleware runs on every request. Register it in bootstrap.rs using the global_middleware! macro:

2. Route Middleware

Apply middleware to individual routes using the .middleware() method:

3. Route Group Middleware

Apply middleware to a group of routes that share a common prefix:

Middleware Execution Order

Middleware executes in the following order:
  1. Global middleware (in registration order)
  2. Route group middleware
  3. Route-level middleware
  4. Route handler
For responses, the order is reversed (post-processing happens in reverse order).

Practical Examples

CORS Middleware

Rate Limiting Middleware

Request Timing Middleware

File Organization

The recommended file structure for middleware:
src/middleware/mod.rs:

Summary