Extension<T> is both an extractor and a response type that works with HTTP extensions to share state across handlers and middleware.
As an extractor
Extension allows handlers to extract values that have been added to request extensions by middleware or layers:
Optional extensions
If an extension might not be present, useOption<Extension<T>>:
As a layer
Extension can be used as a layer to add values to all requests:
As a response
Extension can be returned from handlers to add values to response extensions:
Extension vs State
Extension and State are similar but have important differences:
Prefer
State for application-level state that’s known at compile time. Use Extension for values added by middleware or for multiple independent shared values.Type requirements
The typeT in Extension<T> must be:
Clone- Values are cloned when extractedSend + Sync- Required for async handlers'static- Cannot contain non-static references
Rejection
Rejects withMissingExtension when:
- The extension type wasn’t added via layer or middleware
- A previous extractor removed it from request extensions
Example: Request ID middleware
See also
- State - Recommended way to share application state
- ConnectInfo - Extract connection metadata