Skip to main content

Module middleware

Module middleware 

Source
Expand description

Middleware.

A middleware is any async fn(Request, Next) -> Response:

ⓘ
pub async fn middleware(req: Request, next: Next) -> Response {
    let start = std::time::Instant::now();
    let res = next.run(req).await;
    res.with_header("x-elapsed", &format!("{:?}", start.elapsed()))
}

Execution order for a request to /dashboard/settings:

  1. global middleware registered with App::middleware (in order)
  2. app/middleware.rs (runs before routing, so it may rewrite the path)
  3. nested middleware.rs files from the outermost to the innermost matched segment (e.g. app/dashboard/middleware.rs)
  4. the page, API handler or server action

Structs§

Cors
CORS configuration.
FnMiddleware
Wrap a middleware function pointer generated from middleware.rs.
Next
The rest of the chain.
RateLimit
Fixed-window-with-token-bucket rate limiter configuration.
RequestId
Request identifier inserted by request_id.

Constants§

STRICT_CSP
The policy [security] csp = "strict" stands for: scripts only with the per-request nonce ('strict-dynamic' lets those scripts load modules and islands), everything else from this origin, no plugins, no framing by other sites, forms only to this origin. Inline style attributes stay allowed: components set widths and custom properties with them.

Traits§

Endpoint
Terminal handler at the end of a middleware chain.
Middleware
Middleware trait; implemented for all matching async functions/closures.

Functions§

cors
CORS middleware, including preflight handling.
csrf
Double-submit CSRF token protection for unsafe methods.
protected
Protect routes: when check returns false the user is redirected to login (with ?next= set) — or receives 401 for non-GET requests.
rate_limit
In-memory token bucket rate limiting (per process). Responds 429 with Retry-After when exhausted. For multi-instance deployments, implement your own middleware backed by a shared store.
request_id
Ensure every request has an x-request-id (reused from the client when it is a short, safe token) and echo it on the response.
security_headers
Middleware form of the security headers (for custom setups).

Type Aliases§

BoxFuture
KeyFn
Key extractor for rate limiting.