Skip to main content
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, use Option<Extension<T>>:
If you extract Extension<T> (without Option) and the extension is missing, the request will be rejected with a 500 Internal Server Error.

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 type T in Extension<T> must be:
  • Clone - Values are cloned when extracted
  • Send + Sync - Required for async handlers
  • 'static - Cannot contain non-static references

Rejection

Rejects with MissingExtension when:
  • The extension type wasn’t added via layer or middleware
  • A previous extractor removed it from request extensions
Error message:

Example: Request ID middleware

See also

  • State - Recommended way to share application state
  • ConnectInfo - Extract connection metadata