Axum / Chapter 4 of 4

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.

3 topicsUpdated
29 / 31

Feature flags#

Cargo features remove unused optional code. Defaults cover ordinary HTTP/1 JSON applications; enable specialized features explicitly.

Axum featureEnablesDefault?
http1Hyper HTTP/1 supportyes
http2Hyper HTTP/2 supportno
jsonJson extractor/response and helpersyes
formForm extractor/responseyes
queryQuery extractoryes
matched-pathMatchedPath capture/extractoryes
original-uriOriginalUri capture/extractoryes
tokioserve, SSE, and connect-info APIsyes
tower-logTower log integrationyes
tracingBuilt-in extractor rejection logsyes
macrosDebug and derive macrosno
multipartMultipart extractor and field typesno
wsWebSocket upgrade, socket, and message typesno

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.

30 / 31

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.

31 / 31

Common mistakes#

Most early Axum problems come from request-body ownership, state types, blocking work, or layer placement.

SymptomCauseFix
Handler trait errorWrong extractor order, non-Send future, or unsupported argument/return typeAdd #[debug_handler]; put the body extractor last
Cannot serve Router<AppState>The router is still missing stateCall with_state(state) and return Router/Router<()>
Body already consumedTwo extractors tried to read the bodyUse one body extractor, then parse its buffered value yourself
Large JSON/upload rejectedDefault or explicit body limitSet a justified limit; stream large inputs
Other requests freezeBlocking or CPU-heavy work on a Tokio core threadUse async APIs, spawn_blocking, or a CPU pool
Future is not SendA lock guard or Rc is held across awaitDrop the guard before await; use Arc and appropriate locking
Unknown routes return 401Auth applied with layerUse route_layer for matched routes only
Invalid business values reach the databaseSerde parsing was mistaken for validationAdd explicit validation rules before business logic
Cookie login works but unsafe actions are forgeableSession authentication was added without CSRF defensesUse SameSite, Origin checks, and a CSRF token where required
Rate limit changes with replica countEach process has an independent in-memory limiterMove the global limit to a gateway/shared backend or account for replicas
Metrics system runs out of memoryRaw paths or user IDs became metric labelsLabel with MatchedPath and other bounded values
URI rewrite has no effectRouter layers run after route matchingWrap the middleware around the whole Router service
Wrong client IPConnectInfo sees a proxyUse trusted proxy headers with a strict trust boundary
Timeout closes connectionFallible middleware error was not convertedPlace HandleErrorLayer around the fallible layer
State disappears in nested routerInner and outer routers need different missing-state typesProvide/convert state before nesting or use FromRef
WebSocket task leaksDetached read/write task survives its peerCancel 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.

Axum runs on Tokio and uses Hyper for HTTP and Tower for service middleware.