| name | litestar-middleware |
| description | Auto-activate for ASGIMiddleware, DefineMiddleware, middleware=, CORSConfig, CSRFConfig, AllowedHostsConfig, CompressionConfig, request IDs, or ASGI scopes. Not for route logic. |
Litestar Middleware
Use this skill for built-in middleware config, custom ASGI middleware, request lifecycle hooks, and auth user loading.
Code Style Rules
- Use built-in middleware configs before custom middleware.
- Keep middleware focused on cross-cutting request behavior.
- Filter by ASGI scope when middleware applies only to HTTP or WebSocket.
- Keep business policy in Guards and services.
Quick Reference
Workflow
- Decide whether a built-in config solves the need.
- Choose custom middleware only for cross-cutting behavior.
- Set ordering deliberately.
- Verify HTTP and WebSocket behavior separately when both apply.
Guardrails
- Do not put business workflows in middleware.
- Do not apply HTTP-only middleware to WebSocket scopes.
- Do not mutate request state without documenting the key.
- Do not duplicate Guard policy in middleware.
Validation Checkpoint
Example
from litestar.middleware import ASGIMiddleware
middleware = [RequestIDMiddleware()]
References Index
Official References
Shared Styleguide Baseline