Feature flags and API reference
Choose Axum feature flags and look up routing, extractor, and response APIs. Check common mistakes before wiring an HTTP service.
Feature flags#
Cargo features remove unused optional code. Defaults cover ordinary HTTP/1 JSON applications; enable specialized features explicitly.
| Axum feature | Enables | Default? |
|---|---|---|
| http1 | Hyper HTTP/1 support | yes |
| http2 | Hyper HTTP/2 support | no |
| json | Json extractor/response and helpers | yes |
| form | Form extractor/response | yes |
| query | Query extractor | yes |
| matched-path | MatchedPath capture/extractor | yes |
| original-uri | OriginalUri capture/extractor | yes |
| tokio | serve, SSE, and connect-info APIs | yes |
| tower-log | Tower log integration | yes |
| tracing | Built-in extractor rejection logs | yes |
| macros | Debug and derive macros | no |
| multipart | Multipart extractor and field types | no |
| ws | WebSocket upgrade, socket, and message types | no |
Tokio features Axum apps commonly need
rt-multi-threadmacrosnetsignaltimesyncfsio-util
For an application, tokio = { version = "1", features = ["full"] } is the simplest start. Library authors should select only the features their library directly requires.
Complete API map#
Axum modules, public types, traits, and functions, grouped by purpose.
Crate root
Types: Router, Json, Form, Extension, Error, BoxError.
Traits: RequestExt, RequestPartsExt, ServiceExt.
Function: serve. Macros: debug_handler, debug_middleware. Re-export: http.
body
Body, BodyDataStream, Bytes, HttpBody, and to_bytes. Construct bodies from strings, bytes, streams, or another HTTP body; consume them as frames or data streams.
extract
Core traits: FromRequest, FromRequestParts, OptionalFromRequest, OptionalFromRequestParts, FromRef.
Common types: Request, Path, Query, Json, Form, State, Extension, ConnectInfo, DefaultBodyLimit, MatchedPath, NestedPath, OriginalUri, RawForm, RawPathParams, RawQuery, Multipart, WebSocketUpgrade.
Submodules: connect_info, multipart, path, rejection, ws.
Derives: FromRef, FromRequest, FromRequestParts.
extract::connect_info
ConnectInfo, Connected, IntoMakeServiceWithConnectInfo, MockConnectInfo, and its ResponseFuture. Implement Connected to derive custom metadata from accepted connections.
extract::multipart
Multipart, Field, MultipartError, InvalidBoundary, and MultipartRejection. Iterate with next_field; consume a field as bytes, text, or chunks.
extract::path
Path, RawPathParams, RawPathParamsIter, FailedToDeserializePathParams, InvalidUtf8InPathParam, and ErrorKind.
extract::rejection
BytesRejection, ExtensionRejection, FailedToBufferBody, FormRejection, JsonRejection, MatchedPathRejection, NestedPathRejection, PathRejection, QueryRejection, RawFormRejection, RawPathParamsRejection, StringRejection.
Specific causes include FailedToDeserializeForm, FailedToDeserializeFormBody, FailedToDeserializeQueryString, InvalidFormContentType, InvalidUtf8, JsonDataError, JsonSyntaxError, LengthLimitError, MatchedPathMissing, MissingExtension, MissingJsonContentType, MissingPathParams, and UnknownBodyError.
extract::ws
WebSocketUpgrade, WebSocket, Message, CloseFrame, CloseCode, Utf8Bytes, OnFailedUpgrade, DefaultOnFailedUpgrade, close-code constants, and WebSocket-specific rejections.
Upgrade configuration includes protocols, write-buffer size, maximum write-buffer size, maximum message size, maximum frame size, acceptance of unmasked frames, failed-upgrade handling, and on_upgrade.
handler
Handler, HandlerWithoutStateExt, HandlerService, Layered, and handler future types. Important methods include call, layer, with_state, and into_service.
middleware
Constructors: from_fn, from_fn_with_state, from_extractor, from_extractor_with_state, map_request, map_request_with_state, map_response, map_response_with_state.
Types: AddExtension, FromExtractor, FromExtractorLayer, FromFn, FromFnLayer, MapRequest, MapRequestLayer, MapResponse, MapResponseLayer, Next, ResponseAxumBody, ResponseAxumBodyFuture, ResponseAxumBodyLayer.
Trait: IntoMapRequestResult. The future module contains middleware future types.
response
IntoResponse, IntoResponseParts, Response, ResponseParts, Result, ErrorResponse, Html, Json, Form, Extension, AppendHeaders, NoContent, Redirect, and Sse.
SSE types: Event, EventDataWriter, KeepAlive, KeepAliveStream, and Sse.
routing
Handler functions: any, connect, delete, get, head, on, options, patch, post, put, trace.
Service variants: any_service, connect_service, delete_service, get_service, head_service, on_service, options_service, patch_service, post_service, put_service, trace_service.
Types: Router, MethodRouter, MethodFilter, Route, IntoMakeService, RouterAsService, RouterIntoService, and routing future types.
Router operations: new, route, route_service, nest, nest_service, merge, layer, route_layer, has_routes, fallback, fallback_service, with_state, as_service, into_service, into_make_service, into_make_service_with_connect_info, and without_v07_checks.
MethodRouter operations: method chaining, on, on_service, fallback, fallback_service, layer, with_state, and conversion to a service.
serve
serve, Listener, ListenerExt, IncomingStream, Serve, TapIo, and WithGracefulShutdown. ListenerExt::tap_io can inspect or configure accepted I/O before serving it.
error_handling
HandleError, HandleErrorLayer, and error-handling future types. These convert a fallible Tower service error into an infallible HTTP response.
Integrations outside the axum package
tower supplies Service, Layer, ServiceBuilder, readiness, timeout, load shedding, buffering, and test helpers. tower-http supplies tracing, CORS, compression, static-file services, request IDs, limits, sensitive headers, catch-panic, auth, and path normalization. axum-extra supplies optional typed headers, cookies, protobuf, routing helpers, and other utilities.
sqlx and sea-orm provide database access. jsonwebtoken, argon2, axum-login, and tower-sessions cover common authentication flows. garde plus axum-valid provide request validation; utoipa and utoipa-axum generate OpenAPI; tower-governor rate-limits requests; tracing records structured diagnostics; and axum-server can serve TLS directly. These are related crates, not Axum core.
Common mistakes#
Most early Axum problems come from request-body ownership, state types, blocking work, or layer placement.
| Symptom | Cause | Fix |
|---|---|---|
| Handler trait error | Wrong extractor order, non-Send future, or unsupported argument/return type | Add #[debug_handler]; put the body extractor last |
| Cannot serve Router<AppState> | The router is still missing state | Call with_state(state) and return Router/Router<()> |
| Body already consumed | Two extractors tried to read the body | Use one body extractor, then parse its buffered value yourself |
| Large JSON/upload rejected | Default or explicit body limit | Set a justified limit; stream large inputs |
| Other requests freeze | Blocking or CPU-heavy work on a Tokio core thread | Use async APIs, spawn_blocking, or a CPU pool |
| Future is not Send | A lock guard or Rc is held across await | Drop the guard before await; use Arc and appropriate locking |
| Unknown routes return 401 | Auth applied with layer | Use route_layer for matched routes only |
| Invalid business values reach the database | Serde parsing was mistaken for validation | Add explicit validation rules before business logic |
| Cookie login works but unsafe actions are forgeable | Session authentication was added without CSRF defenses | Use SameSite, Origin checks, and a CSRF token where required |
| Rate limit changes with replica count | Each process has an independent in-memory limiter | Move the global limit to a gateway/shared backend or account for replicas |
| Metrics system runs out of memory | Raw paths or user IDs became metric labels | Label with MatchedPath and other bounded values |
| URI rewrite has no effect | Router layers run after route matching | Wrap the middleware around the whole Router service |
| Wrong client IP | ConnectInfo sees a proxy | Use trusted proxy headers with a strict trust boundary |
| Timeout closes connection | Fallible middleware error was not converted | Place HandleErrorLayer around the fallible layer |
| State disappears in nested router | Inner and outer routers need different missing-state types | Provide/convert state before nesting or use FromRef |
| WebSocket task leaks | Detached read/write task survives its peer | Cancel sibling tasks when one half closes |
Source of truth
This sheet targets Axum 0.8.9, Tokio 1.53.1, SQLx 0.9, SeaORM 2.0, tower-http 0.7, Garde 0.23, axum-valid 0.25, utoipa 5.5, utoipa-axum 0.2, tower-sessions 0.15, axum-login 0.18, tower-governor 0.8, axum-server 0.8, jsonwebtoken 11, and argon2 0.6.
For exact trait bounds and newer APIs, check the official Axum documentation, Tokio documentation, tower-http documentation, SQLx documentation, SeaORM documentation, Garde documentation, Utoipa documentation, tower-sessions documentation, and official Axum examples.
Help improve CodeRef
Allow Google Analytics to measure page visits and use of the guides? It uses cookies after you accept. Your choice won’t affect access to the site. Privacy notice