litestar-middleware
Middleware
Execution Workflow
- Confirm the requirement is really middleware-worthy: broad ASGI wrapping, not route business logic.
- Prefer built-in config-based middleware first.
- Choose the right layer and ordering deliberately.
- Decide whether the concern belongs in middleware, lifecycle hooks, or route logic.
- For custom middleware, choose the simplest correct implementation style.
- Validate both success and exception-generated responses, plus exclusions and scope handling.
Core Rules
- Keep middleware focused on one cross-cutting concern.
- Prefer built-in middleware/config objects before creating custom implementations.
- Treat middleware order as part of API behavior.
- Keep middleware scope-aware for
http,websocket, andlifespanas needed. - Use lifecycle hooks when the job is response-object mutation rather than ASGI message wrapping.
- Keep middleware non-blocking and ASGI-compliant.
- Keep
404and405expectations explicit because those router-generated exceptions occur before the middleware stack.
Decision Guide
- Use built-in config middleware for CORS, CSRF, compression, rate limiting, logging, sessions, and allowed hosts.
- Use a middleware factory for very small wrappers.
- Use
ASGIMiddlewarefor configurable production custom middleware. - Use
MiddlewareProtocolfor minimal low-level behavior. - Use
AbstractMiddlewareonly for compatibility or migration scenarios. - Use
DefineMiddlewarewhen constructor-style args must be supplied to a middleware factory or class. - Use
litestar-lifecycle-hooksinstead when the behavior belongs toafter_request,before_send, or related hook stages.
Reference Files
Read only the sections you need:
- For middleware fundamentals, ordering, exclusions, and built-in middleware selection, read references/builtin-and-ordering.md.
- For custom middleware implementation styles,
ASGIMiddleware,MiddlewareProtocol,AbstractMiddleware, andDefineMiddleware, read references/custom-middleware-patterns.md.
Recommended Defaults
- Start with one middleware concern at a time.
- Keep built-in config values explicit and reviewed.
- Keep exclusions and
opt-based skips narrow and tested. - Make ordering assumptions visible in code comments only when they are truly non-obvious.
- Test middleware against both successful and failing downstream handlers.
Anti-Patterns
- Putting route-specific business rules into middleware.
- Creating custom middleware when a built-in config or lifecycle hook already fits.
- Ignoring middleware order when several wrappers interact.
- Mutating request or response state at the wrong ASGI stage.
- Assuming router-generated
404and405pass through middleware. - Letting middleware silently depend on undocumented
optexclusions or path patterns.
Validation Checklist
- Confirm middleware is attached at the intended layer only.
- Confirm order matches both layer precedence and list order.
- Confirm exclusions via path patterns,
exclude_opt_key, or scopes behave as intended. - Confirm behavior is correct for both success and exception-generated responses.
- Confirm
404and405behavior is handled at the right boundary. - Confirm custom middleware remains ASGI-compliant and non-blocking.
- Confirm built-in security and logging middleware settings align with deployment expectations.
Cross-Skill Handoffs
- Use
litestar-lifecycle-hooksfor hook-stage logic rather than raw ASGI wrapping. - Use
litestar-authentication,litestar-security,litestar-logging, andlitestar-metricsfor domain-specific middleware outcomes. - Use
litestar-debuggingwhen middleware interactions are the source of a runtime defect. - Use
litestar-routingwhen middleware behavior depends on layer placement oroptstrategy.
Litestar References
More from alti3/litestar-skills
litestar-responses
Build Litestar responses with typed return values, explicit Response containers, layered response classes, headers, cookies, status-code control, redirects, files, streams, server-sent events, ASGI app returns, and background tasks. Use when shaping outbound HTTP behavior, correcting response contracts, or choosing the right Litestar response primitive. Do not use for request parsing, validation, or authentication policy design.
22litestar-logging
Configure Litestar logging with `LoggingConfig`, `queue_listener`, exception logging policy, selective stack-trace suppression, standard logging, picologging, Structlog, and custom logging config subclasses. Use when establishing or refactoring application logging behavior, request-level logs, or production-safe error logging in Litestar. Do not use for metrics/tracing instrumentation or exception-response contract design.
22litestar-authentication
Implement Litestar authentication with custom authentication middleware, built-in security backends, JWT and session flows, route inclusion and exclusion rules, and typed auth context on `Request` / `ASGIConnection`. Use when establishing identity, issuing or validating credentials, or attaching authenticated user context in Litestar. Do not use for generic request parsing, broad security audits, or unrelated transport concerns.
22litestar-routing
Design and implement Litestar routing with app/router/controller composition, handler decorators, path and parameter modeling, route indexing/reverse lookups, ASGI mounting, and layered route metadata. Use when creating or refactoring endpoint topology and URL contracts. Do not use for purely internal service logic unrelated to HTTP route structure.
18litestar-dto
Configure Litestar DTO behavior for inbound parsing and outbound serialization, including layer-scoped `dto`/`return_dto`, `DTOConfig` policies, `DTOData` update workflows, and custom `AbstractDTO` implementations. Use when API payload contracts differ from internal model structures. Do not use when internal models can be exposed safely without transformation.
18litestar-openapi
Configure Litestar OpenAPI schema generation and documentation UX with `OpenAPIConfig`, route-level schema metadata, schema generation controls, operation customization, UI render plugins, and documentation endpoint strategy. Use when API contract and docs quality must be implemented or corrected, especially for request, auth, and metrics surfaces. Do not use for runtime business logic changes unrelated to schema or documentation.
17