axum
HTTP routing and request handling library that focuses on ergonomics and modularity
0.8.9
436M downloads/mo
#264 most downloaded on crates.io
tokio-rs/axum
What this package is like to depend on
Last release 4 months ago
14 Apr 2026
Release timing varies
gaps range from 2 weeks to 5 months
Nearly every release is documented
notes for 81 of 83 stable releases
5 versions withdrawn
withdrawn after publishing
5 years old
94 releases · first in 2021
5 releases in the last 12 months
see the full history below
Release timeline
94 releases · Jul 2021 to Apr 2026Releases
latest 60 of 94-
0.8.914 Apr 2026Release notes
Open source →- added:
WebSocketUpgrade::{requested_protocols, set_selected_protocol}for more flexible subprotocol selection (#3597) - changed: Update minimum rust version to 1.80 (#3620)
- fixed: Set connect endpoint on correct field in MethodRouter (#3656)
- fixed: Return specific error message when multipart body limit is exceeded (#3611)
Release notes
Open source →- added:
WebSocketUpgrade::{requested_protocols, set_selected_protocol}for more flexible subprotocol selection (#3597) - changed: Update minimum rust version to 1.80 (#3620)
- fixed: Set connect endpoint on correct field in MethodRouter (#3656)
- fixed: Return specific error message when multipart body limit is exceeded (#3611)
- added:
-
0.8.820 Dec 2025 -
0.8.714 Nov 2025 -
0.8.630 Sep 2025 -
0.8.528 Sep 2025Release notes
Open source →- fixed: Reject JSON request bodies with trailing characters after the JSON document (#3453)
- added: Implement
OptionalFromRequestforMultipart(#3220) - added: Getter methods
Location::{status_code, location} - added: Support for writing arbitrary binary data into server-sent events (#3425)]
- added:
middleware::ResponseAxumBodyLayerfor mapping response body toaxum::body::Body(#3469) - added:
impl FusedStream for WebSocket(#3443) - changed: The
ssemodule andSsetype no longer depend on thetokiofeature (#3154) - changed: If the location given to one of
Redirects constructors is not a valid header value, instead of panicking on construction, theIntoResponseimpl now returns an HTTP 500, just likeJsondoes when serialization fails (#3377) - changed: Update minimum rust version to 1.78 (#3412)
-
0.8.430 Apr 2025 -
0.8.328 Mar 2025Release notes
Open source →- added: Implement
From<Bytes>forMessage(#3273) - added: Implement
OptionalFromRequestforJson(#3142) - added: Implement
OptionalFromRequestforExtension(#3157) - added: Allow setting the read buffer capacity of
WebSocketUpgrade(#3178) - changed: Improved code size / compile time of dependent crates (#3285, #3294)
- added: Implement
-
0.8.221 Jan 2025 withdrawnRelease notes
Open source →Yanked from crates.io due to unforeseen breaking change, see #3190 for details.
-
0.8.101 Jan 2025 -
0.8.001 Jan 2025Release notes
Open source →since rc.1
<details>
- breaking:
axum::extract::ws::Messagenow usesBytesin place ofVec<u8>, and a newUtf8Bytestype in place ofString, for its variants (#3078) - breaking: Remove
OptionalFromRequestPartsimpl forQuery(#3088) - changed: Upgraded
tokio-tungsteniteto 0.26 (#3078) - changed: Query/Form: Use
serde_path_to_errorto report fields that failed to parse (#3081)
</details>
full changelog
Note: there are further relevant changes in axum-core's changelog
- breaking: Upgrade matchit to 0.8, changing the path parameter syntax from
/:singleand/*manyto/{single}and/{*many}; the old syntax produces a panic to avoid silent change in behavior (#2645) - breaking: Require
Syncfor all handlers and services added toRouterandMethodRouter(#2473) - breaking: The tuple and tuple_struct
Pathextractor deserializers now check that the number of parameters matches the tuple length exactly (#2931) - breaking: Move
Hostextractor toaxum-extra(#2956) - breaking: Remove
WebSocket::close. Users should explicitly send close messages themselves. (#2974) - breaking: Make
servegeneric over the listener and IO types (#2941) - breaking: Remove
Serve::tcp_nodelayandWithGracefulShutdown::tcp_nodelay. Seeserve::ListenerExtfor an API that let you set arbitrary TCP stream properties. (#2941) - breaking:
Option<Path<T>>no longer swallows all error conditions, instead rejecting the request in many cases; see its documentation for details (#2475) - breaking:
axum::extract::ws::Messagenow usesBytesin place ofVec<u8>, and a newUtf8Bytestype in place ofString, for its variants (#3078) - fixed: Skip SSE incompatible chars of
serde_json::RawValueinEvent::json_data(#2992) - fixed: Don't panic when array type is used for path segment (#3039)
- fixed: Avoid setting
content-lengthbefore middleware. This allows middleware to add bodies to requests without needing to manually setcontent-length(#2897) - change: Update minimum rust version to 1.75 (#2943)
- changed: Upgraded
tokio-tungsteniteto 0.26 (#3078) - changed: Query/Form: Use
serde_path_to_errorto report fields that failed to parse (#3081) - added: Add
method_not_allowed_fallbackto set a fallback when a path matches but there is no handler for the given HTTP method (#2903) - added: Add
NoContentas a self-described shortcut forStatusCode::NO_CONTENT(#2978) - added: Add support for WebSockets over HTTP/2.
They can be enabled by changing
get(ws_endpoint)handlers toany(ws_endpoint)(#2894) - added: Add
MethodFilter::CONNECT,routing::connect[_service]andMethodRouter::connect[_service](#2961) - added: Extend
FailedToDeserializePathParams::kindenum with (ErrorKind::DeserializeError) This new variant captures bothkey,value, andmessagefrom named path parameters parse errors, instead of only deserialization error message inErrorKind::Message. (#2720)
rc.1
Note: there are further relevant changes in axum-core's changelog
- breaking: Move
Hostextractor toaxum-extra(#2956) - breaking: Remove
WebSocket::close. Users should explicitly send close messages themselves. (#2974) - breaking: Make
servegeneric over the listener and IO types (#2941) - breaking: Remove
Serve::tcp_nodelayandWithGracefulShutdown::tcp_nodelay. Seeserve::ListenerExtfor an API that let you set arbitrary TCP stream properties. (#2941) - breaking:
Option<Path<T>>andOption<Query<T>>no longer swallow all error conditions, instead rejecting the request in many cases; see their documentation for details (#2475) - fixed: Skip SSE incompatible chars of
serde_json::RawValueinEvent::json_data(#2992) - fixed: Don't panic when array type is used for path segment (#3039)
- fixed: Avoid setting
content-lengthbefore middleware. This allows middleware to add bodies to requests without needing to manually setcontent-length(#2897) - added: Add
method_not_allowed_fallbackto set a fallback when a path matches but there is no handler for the given HTTP method (#2903) - added: Add
NoContentas a self-described shortcut forStatusCode::NO_CONTENT(#2978) - added: Add support for WebSockets over HTTP/2.
They can be enabled by changing
get(ws_endpoint)handlers toany(ws_endpoint)(#2894) - added: Add
MethodFilter::CONNECT,routing::connect[_service]andMethodRouter::connect[_service](#2961) - added: Extend
FailedToDeserializePathParams::kindenum with (ErrorKind::DeserializeError) This new variant captures bothkey,value, andmessagefrom named path parameters parse errors, instead of only deserialization error message inErrorKind::Message. (#2720)
alpha.1
- breaking: Require
Syncfor all handlers and services added toRouterandMethodRouter(#2473) - breaking: The tuple and tuple_struct
Pathextractor deserializers now check that the number of parameters matches the tuple length exactly (#2931) - breaking: Upgrade matchit to 0.8, changing the path parameter syntax from
/:singleand/*manyto/{single}and/{*many}; the old syntax produces a panic to avoid silent change in behavior (#2645) - change: Update minimum rust version to 1.75 (#2943)
- breaking:
-
0.8.0-rc.117 Dec 2024 pre-releaseNothing published for this version
-
0.8.0-alpha.105 Oct 2024 pre-releaseNothing published for this version
-
0.7.916 Nov 2024 -
0.7.815 Nov 2024Release notes
Open source →- fixed: Skip SSE incompatible chars of
serde_json::RawValueinEvent::json_data(#2992) - added: Add
method_not_allowed_fallbackto set a fallback when a path matches but there is no handler for the given HTTP method (#2903) - added: Add
MethodFilter::CONNECT,routing::connect[_service]andMethodRouter::connect[_service](#2961) - added: Add
NoContentas a self-described shortcut forStatusCode::NO_CONTENT(#2978)
- fixed: Skip SSE incompatible chars of
-
0.7.727 Sep 2024Release notes
Open source →- change: Remove manual tables of content from the documentation, since rustdoc now generates tables of content in the sidebar (#2921)
-
0.7.620 Sep 2024Release notes
Open source →- change: Avoid cloning
Arcduring deserialization ofPath - added:
axum::serve::Serve::tcp_nodelayandaxum::serve::WithGracefulShutdown::tcp_nodelay(#2653) - added:
Router::has_routesfunction (#2790) - change: Update tokio-tungstenite to 0.23 (#2841)
- added:
Serve::local_addrandWithGracefulShutdown::local_addrfunctions (#2881)
- change: Avoid cloning
-
0.7.524 Mar 2024 -
0.7.413 Jan 2024 -
0.7.329 Dec 2023Release notes
Open source →- added:
BodyimplementsFrom<()>now (#2411) - change: Update version of multer used internally for multipart (#2433)
- change: Update tokio-tungstenite to 0.21 (#2435)
- added: Enable
tracingfeature by default (#2460) - added: Support graceful shutdown on
serve(#2398) - added:
RouterIntoServiceimplementsClone(#2456)
- added:
-
0.7.204 Dec 2023Release notes
Open source → -
0.7.127 Nov 2023 -
0.7.027 Nov 2023Release notes
Open source →- breaking: Update public dependencies. axum now requires
- breaking: axum now requires tower-http 0.5
- breaking: Remove deprecated
WebSocketUpgrade::max_send_queue - breaking: The following types/traits are no longer generic over the request body
(i.e. the
Btype param has been removed) (#1751 and #1789):FromRequestPartsFromRequestHandlerServiceHandlerWithoutStateExtHandlerLayeredFutureLayeredMethodRouterNextRequestExtRouteFutureRouteRouter
- breaking: axum no longer re-exports
hyper::Bodyas that type is removed in hyper 1.0. Instead axum has its own body type ataxum::body::Body(#1751) - breaking:
extract::BodyStreamhas been removed asbody::BodyimplementsStreamandFromRequestdirectly (#1751) - breaking: Change
sse::Event::json_datato useaxum_core::Erroras its error type (#1762) - breaking: Rename
DefaultOnFailedUpdgradetoDefaultOnFailedUpgrade(#1664) - breaking: Rename
OnFailedUpdgradetoOnFailedUpgrade(#1664) - breaking:
TypedHeaderhas been moved toaxum-extraasaxum_extra::TypedHeaderand requires enabling thetyped-headerfeature onaxum-extra. Theheadersfeature has been removed from axum; what it provided underaxum::headersis now found inaxum_extra::headersby default. (#1850) - breaking: Removed re-exports of
EmptyandFull. Useaxum::body::Body::emptyandaxum::body::Body::fromrespectively (#1789) - breaking: The response returned by
IntoResponse::into_responsemust useaxum::body::Bodyas the body type.axum::response::Responsedoes this (#1789) - breaking: Removed the
BoxBodytype alias and itsbox_bodyconstructor. Useaxum::body::Body::newinstead (#1789) - breaking: Remove
RawBodyextractor.axum::body::BodyimplementsFromRequestdirectly (#1789) - breaking: The following types from
http-bodyno longer implementIntoResponse:Full, useBody::frominsteadEmpty, useBody::emptyinsteadBoxBody, useBody::newinsteadUnsyncBoxBody, useBody::newinsteadMapData, useBody::newinsteadMapErr, useBody::newinstead
- added: Add
axum::extract::Requesttype alias where the body isaxum::body::Body(#1789) - added: Add
Router::as_serviceandRouter::into_serviceto workaround type inference issues when callingServiceExtmethods on aRouter(#1835) - breaking: Removed
axum::Serveras it was removed in hyper 1.0. Instead useaxum::serve(listener, service)or hyper/hyper-util for more configuration options (#1868) - breaking: Only inherit fallbacks for routers nested with
Router::nest. Routers nested withRouter::nest_servicewill no longer inherit fallbacks (#1956) - fixed: Don't remove the
Sec-WebSocket-Keyheader inWebSocketUpgrade(#1972) - added: Add
axum::extract::Query::try_from_uri(#2058) - added: Implement
IntoResponseforBox<str>andBox<[u8]>([#2035]) - breaking: Simplify
MethodFilter. It no longer uses bitflags (#2073) - fixed: Fix bugs around merging routers with nested fallbacks (#2096)
- fixed: Fix
.source()of composite rejections (#2030) - fixed: Allow unreachable code in
#[debug_handler](#2014) - change: axum's MSRV is now 1.66 (#1882)
- added: Implement
IntoResponsefor(R,) where R: IntoResponse(#2143) - changed: For SSE, add space between field and value for compatibility (#2149)
- added: Add
NestedPathextractor (#1924) - added: Add
handle_errorfunction to existingServiceExttrait (#2235) - breaking:
impl<T> IntoResponse(Parts) for Extension<T>now requiresT: Clone, as that is required by the http crate (#1882) - added: Add
axum::Json::from_bytes(#2244) - added: Implement
FromRequestPartsforhttp::request::Parts(#2328) - added: Implement
FromRequestPartsforhttp::Extensions(#2328) - fixed: Clearly document applying
DefaultBodyLimitto individual routes (#2157)
-
0.6.2003 Aug 2023Release notes
Open source →- added:
WebSocketUpgrade::write_buffer_sizeandWebSocketUpgrade::max_write_buffer_size - changed: Deprecate
WebSocketUpgrade::max_send_queue - change: Update tokio-tungstenite to 0.20
- added: Implement
HandlerforT: IntoResponse(#2140)
- added:
-
0.6.1917 Jul 2023Release notes
Open source →- added: Add
axum::extract::Query::try_from_uri(#2058) - added: Implement
IntoResponseforBox<str>andBox<[u8]>(#2035) - fixed: Fix bugs around merging routers with nested fallbacks (#2096)
- fixed: Fix
.source()of composite rejections (#2030) - fixed: Allow unreachable code in
#[debug_handler](#2014) - change: Update tokio-tungstenite to 0.19 (#2021)
- change: axum's MSRV is now 1.63 (#2021)
- added: Add
-
0.6.1830 Apr 2023Release notes
Open source →- fixed: Don't remove the
Sec-WebSocket-Keyheader inWebSocketUpgrade(#1972)
- fixed: Don't remove the
-
0.6.1725 Apr 2023 -
0.6.1618 Apr 2023 -
0.6.1512 Apr 2023 -
0.6.1411 Apr 2023 -
0.6.1311 Apr 2023Release notes
Open source →- added: Log rejections from built-in extractors with the
axum::rejection=tracetarget (#1890) - fixed: Fixed performance regression with
Router::nestintroduced in 0.6.0.nestnow flattens the routes which performs better (#1711) - fixed: Extracting
MatchedPathin nested handlers now gives the full matched path, including the nested path (#1711) - added: Implement
DerefandDerefMutfor built-in extractors (#1922)
- added: Log rejections from built-in extractors with the
-
0.6.1222 Mar 2023 -
0.6.1113 Mar 2023 -
0.6.1003 Mar 2023 -
0.6.927 Feb 2023Release notes
Open source →- changed: Update to tower-http 0.4. axum is still compatible with tower-http 0.3 (#1783)
-
0.6.824 Feb 2023 -
0.6.717 Feb 2023 -
0.6.612 Feb 2023 -
0.6.511 Feb 2023 -
0.6.424 Jan 2023 -
0.6.320 Jan 2023Release notes
Open source →- added: Implement
IntoResponsefor&'static [u8; N]and[u8; N](#1690) - fixed: Make
Pathsupport types usingserde::Deserializer::deserialize_any(#1693) - added: Add
RawPathParams(#1713) - added: Implement
CloneandServiceforaxum::middleware::Next(#1712) - fixed: Document required tokio features to run "Hello, World!" example (#1715)
- added: Implement
-
0.6.209 Jan 2023 -
0.6.129 Nov 2022 -
0.6.025 Nov 2022Release notes
Open source →Routing
-
fixed: Nested routers are now allowed to have fallbacks (#1521):
let api_router = Router::new() .route("/users", get(|| { ... })) .fallback(api_fallback); let app = Router::new() // this would panic in 0.5 but in 0.6 it just works // // requests starting with `/api` but not handled by `api_router` // will go to `api_fallback` .nest("/api", api_router);The outer router's fallback will still apply if a nested router doesn't have its own fallback:
// this time without a fallback let api_router = Router::new().route("/users", get(|| { ... })); let app = Router::new() .nest("/api", api_router) // `api_router` will inherit this fallback .fallback(app_fallback); -
breaking: The request
/foo/no longer matches/foo/*rest. If you want to match/foo/you have to add a route specifically for that (#1086)For example:
use axum::{Router, routing::get, extract::Path}; let app = Router::new() // this will match `/foo/bar/baz` .route("/foo/*rest", get(handler)) // this will match `/foo/` .route("/foo/", get(handler)) // if you want `/foo` to match you must also add an explicit route for it .route("/foo", get(handler)); async fn handler( // use an `Option` because `/foo/` and `/foo` don't have any path params params: Option<Path<String>>, ) {} -
breaking: Path params for wildcard routes no longer include the prefix
/. e.g./foo.jswill match/*filepathwith a value offoo.js, not/foo.js(#1086)For example:
use axum::{Router, routing::get, extract::Path}; let app = Router::new().route("/foo/*rest", get(handler)); async fn handler( Path(params): Path<String>, ) { // for the request `/foo/bar/baz` the value of `params` will be `bar/baz` // // on 0.5 it would be `/bar/baz` } -
fixed: Routes like
/fooand/*restare no longer considered overlapping./foowill take priority (#1086)For example:
use axum::{Router, routing::get}; let app = Router::new() // this used to not be allowed but now just works .route("/foo/*rest", get(foo)) .route("/foo/bar", get(bar)); async fn foo() {} async fn bar() {} -
breaking: Automatic trailing slash redirects have been removed. Previously if you added a route for
/foo, axum would redirect calls to/foo/to/foo(or vice versa for/foo/):use axum::{Router, routing::get}; let app = Router::new() // a request to `GET /foo/` will now get `404 Not Found` // whereas in 0.5 axum would redirect to `/foo` // // same goes the other way if you had the route `/foo/` // axum will no longer redirect from `/foo` to `/foo/` .route("/foo", get(handler)); async fn handler() {}Either explicitly add routes for
/fooand/foo/or useaxum_extra::routing::RouterExt::route_with_tsrif you want the old behavior (#1119) -
breaking:
Router::fallbacknow only acceptsHandlers (similarly to whatget,post, etc. accept). Use the newRouter::fallback_servicefor setting anyServiceas the fallback (#1155)This fallback on 0.5:
use axum::{Router, handler::Handler}; let app = Router::new().fallback(fallback.into_service()); async fn fallback() {}Becomes this in 0.6
use axum::Router; let app = Router::new().fallback(fallback); async fn fallback() {} -
breaking: It is no longer supported to
nesttwice at the same path, i.e..nest("/foo", a).nest("/foo", b)will panic. Instead use.nest("/foo", a.merge(b)) -
breaking: It is no longer supported to
nesta router and add a route at the same path, such as.nest("/a", _).route("/a", _). Instead use.nest("/a/", _).route("/a", _). -
changed:
Router::nestnow only acceptsRouters, the general-purposeServicenesting method has been renamed tonest_service(#1368) -
breaking: Allow
Error: Into<Infallible>forRoute::{layer, route_layer}(#924) -
breaking:
MethodRouternow panics on overlapping routes (#1102) -
breaking:
Router::routenow only acceptsMethodRouters created withget,post, etc. Use the newRouter::route_servicefor routing to anyServices (#1155) -
breaking: Adding a
.route_layeronto aRouterorMethodRouterwithout any routes will now result in a panic. Previously, this just did nothing. #1327 -
breaking:
RouterServicehas been removed sinceRouternow implementsServicewhen the state is(). UseRouter::with_stateto provide the state and get aRouter<()>. Note thatRouterServiceonly existed in the pre-releases, not 0.5 (#1552)
Extractors
-
added: Added new type safe
Stateextractor. This can be used withRouter::with_stateand gives compile errors for missing states, whereasExtensionwould result in runtime errors (#1155)We recommend migrating from
ExtensiontoStatefor sharing application state since that is more type safe and faster. That is done by usingRouter::with_stateandState.This setup in 0.5
use axum::{routing::get, Extension, Router}; let app = Router::new() .route("/", get(handler)) .layer(Extension(AppState {})); async fn handler(Extension(app_state): Extension<AppState>) {} #[derive(Clone)] struct AppState {}Becomes this in 0.6 using
State:use axum::{routing::get, extract::State, Router}; let app = Router::new() .route("/", get(handler)) .with_state(AppState {}); async fn handler(State(app_state): State<AppState>) {} #[derive(Clone)] struct AppState {}If you have multiple extensions, you can use fields on
AppStateand implementFromRef:use axum::{extract::{State, FromRef}, routing::get, Router}; let state = AppState { client: HttpClient {}, database: Database {}, }; let app = Router::new().route("/", get(handler)).with_state(state); async fn handler( State(client): State<HttpClient>, State(database): State<Database>, ) {} // the derive requires enabling the "macros" feature #[derive(Clone, FromRef)] struct AppState { client: HttpClient, database: Database, } #[derive(Clone)] struct HttpClient {} #[derive(Clone)] struct Database {} -
breaking: It is now only possible for one extractor per handler to consume the request body. In 0.5 doing so would result in runtime errors but in 0.6 it is a compile error (#1272)
axum enforces this by only allowing the last extractor to consume the request.
For example:
use axum::{Json, http::HeaderMap}; // This won't compile on 0.6 because both `Json` and `String` need to consume // the request body. You can use either `Json` or `String`, but not both. async fn handler_1( json: Json<serde_json::Value>, string: String, ) {} // This won't work either since `Json` is not the last extractor. async fn handler_2( json: Json<serde_json::Value>, headers: HeaderMap, ) {} // This works! async fn handler_3( headers: HeaderMap, json: Json<serde_json::Value>, ) {}This is done by reworking the
FromRequesttrait and introducing a newFromRequestPartstrait.If your extractor needs to consume the request body then you should implement
FromRequest, otherwise implementFromRequestParts.This extractor in 0.5:
struct MyExtractor { /* ... */ } impl<B> FromRequest<B> for MyExtractor where B: Send, { type Rejection = StatusCode; async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> { // ... } }Becomes this in 0.6:
use axum::{ extract::{FromRequest, FromRequestParts}, http::{StatusCode, Request, request::Parts}, }; struct MyExtractor { /* ... */ } // implement `FromRequestParts` if you don't need to consume the request body impl<S> FromRequestParts<S> for MyExtractor where S: Send + Sync, { type Rejection = StatusCode; async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> { // ... } } // implement `FromRequest` if you do need to consume the request body impl<S, B> FromRequest<S, B> for MyExtractor where S: Send + Sync, B: Send + 'static, { type Rejection = StatusCode; async fn from_request(req: Request<B>, state: &S) -> Result<Self, Self::Rejection> { // ... } }For an example of how to write an extractor that accepts different
Content-Typessee theparse-body-based-on-content-typeexample. -
added:
FromRequestandFromRequestPartsderive macro re-exports fromaxum-macrosbehind themacrosfeature (#1352) -
added: Add
RequestExtandRequestPartsExtwhich adds convenience methods for running extractors tohttp::Requestandhttp::request::Parts(#1301) -
added:
JsonRejectionnow displays the path at which a deserialization error occurred (#1371) -
added: Add
extract::RawFormfor accessing raw urlencoded query bytes or request body (#1487) -
fixed: Used
400 Bad RequestforFailedToDeserializeQueryStringrejections, instead of422 Unprocessable Entity(#1387) -
changed: The inner error of a
JsonRejectionis nowserde_path_to_error::Error<serde_json::Error>. Previously it wasserde_json::Error(#1371) -
changed: The default body limit now applies to the
Multipartextractor (#1420) -
breaking:
ContentLengthLimithas been removed. UseDefaultBodyLimitinstead (#1400) -
breaking:
RequestPartshas been removed as part of theFromRequestrework (#1272) -
breaking:
BodyAlreadyExtractedhas been removed (#1272) -
breaking: The following types or traits have a new
Stype param which represents the state (#1155):Router, defaults to()MethodRouter, defaults to()FromRequest, no defaultHandler, no default
-
breaking:
MatchedPathcan now no longer be extracted in middleware for nested routes. In previous versions it returned invalid data when extracted from a middleware applied to a nested router.MatchedPathcan still be extracted from handlers and middleware that aren't on nested routers (#1462) -
breaking: Rename
FormRejection::FailedToDeserializeQueryStringtoFormRejection::FailedToDeserializeForm(#1496)
Middleware
- added: Support running extractors on
middleware::from_fnfunctions (#1088) - added: Add
middleware::from_fn_with_stateto enable running extractors that require state (#1342) - added: Add
middleware::from_extractor_with_state(#1396) - added: Add
map_request,map_request_with_statefor transforming the request with an async function (#1408) - added: Add
map_response,map_response_with_statefor transforming the response with an async function (#1414) - added: Support any middleware response that implements
IntoResponse(#1152) - breaking: Remove
extractor_middlewarewhich was previously deprecated. Useaxum::middleware::from_extractorinstead (#1077) - breaking: Require middleware added with
Handler::layerto haveInfallibleas the error type (#1152)
Misc
- added: Support compiling to WASM. See the
simple-router-wasmexample for more details (#1382) - added: Add
ServiceExtwith methods for turning anyServiceinto aMakeServicesimilarly toRouter::into_make_service(#1302) - added: String and binary
Fromimpls have been added toextract::ws::Messageto be more inline withtungstenite(#1421) - added: Add
#[derive(axum::extract::FromRef)](#1430) - added: Add
accept_unmasked_framessetting in WebSocketUpgrade (#1529) - added: Add
WebSocketUpgrade::on_failed_upgradeto customize what to do when upgrading a connection fails (#1539) - fixed: Annotate panicking functions with
#[track_caller]so the error message points to where the user added the invalid route, rather than somewhere internally in axum (#1248) - changed: axum's MSRV is now 1.60 (#1239)
- changed: For methods that accept some
S: Service, the bounds have been relaxed so the response type must implementIntoResponserather than being a literalResponse - breaking: New
tokiodefault feature needed for WASM support. If you don't need WASM support but havedefault_features = falsefor other reasons you likely need to re-enable thetokiofeature (#1382) - breaking:
handler::{WithState, IntoService}are merged into one type, namedHandlerService(#1418)
<details> <summary>0.6.0 Pre-Releases</summary>
-
-
0.6.0-rc.518 Nov 2022 pre-releaseRelease notes
Open source →-
breaking:
Router::with_stateis no longer a constructor. It is instead used to convert the router into aRouterService(#1532)This nested router on 0.6.0-rc.4
Router::with_state(state).route(...);Becomes this in 0.6.0-rc.5
Router::new().route(...).with_state(state); -
breaking:
Router::inherit_statehas been removed. UseRouter::with_stateinstead (#1532) -
breaking:
Router::nestandRouter::mergenow only supports nesting routers that use the same state type as the router they're being merged into. UseFromReffor substates (#1532) -
added: Add
accept_unmasked_framessetting in WebSocketUpgrade (#1529) -
fixed: Nested routers will now inherit fallbacks from outer routers (#1521)
-
added: Add
WebSocketUpgrade::on_failed_upgradeto customize what to do when upgrading a connection fails (#1539)
-
-
0.6.0-rc.409 Nov 2022 pre-releaseRelease notes
Open source →- changed: The inner error of a
JsonRejectionis nowserde_path_to_error::Error<serde_json::Error>. Previously it wasserde_json::Error(#1371) - added:
JsonRejectionnow displays the path at which a deserialization error occurred (#1371) - fixed: Support streaming/chunked requests in
ContentLengthLimit(#1389) - fixed: Used
400 Bad RequestforFailedToDeserializeQueryStringrejections, instead of422 Unprocessable Entity(#1387) - added: Add
middleware::from_extractor_with_state(#1396) - added: Add
DefaultBodyLimit::maxfor changing the default body limit (#1397) - added: Add
map_request,map_request_with_statefor transforming the request with an async function (#1408) - added: Add
map_response,map_response_with_statefor transforming the response with an async function (#1414) - breaking:
ContentLengthLimithas been removed. UseDefaultBodyLimitinstead (#1400) - changed:
Routerno longer implementsService, call.into_service()on it to obtain aRouterServicethat does (#1368) - added: Add
Router::inherit_state, which creates aRouterwith an arbitrary state type without actually supplying the state; such aRoutercan't be turned into a service directly (.into_service()will panic), but can be nested or merged into aRouterwith the same state type (#1368) - changed:
Router::nestnow only acceptsRouters, the general-purposeServicenesting method has been renamed tonest_service(#1368) - added: Support compiling to WASM. See the
simple-router-wasmexample for more details (#1382) - breaking: New
tokiodefault feature needed for WASM support. If you don't need WASM support but havedefault_features = falsefor other reasons you likely need to re-enable thetokiofeature (#1382) - breaking:
handler::{WithState, IntoService}are merged into one type, namedHandlerService(#1418) - changed: The default body limit now applies to the
Multipartextractor (#1420) - added: String and binary
Fromimpls have been added toextract::ws::Messageto be more inline withtungstenite(#1421) - added: Add
#[derive(axum::extract::FromRef)](#1430) - added:
FromRequestandFromRequestPartsderive macro re-exports from [axum-macros] behind themacrosfeature (#1352) - breaking:
MatchedPathcan now no longer be extracted in middleware for nested routes (#1462) - added: Add
extract::RawFormfor accessing raw urlencoded query bytes or request body (#1487) - breaking: Rename
FormRejection::FailedToDeserializeQueryStringtoFormRejection::FailedToDeserializeForm(#1496)
- changed: The inner error of a
-
0.6.0-rc.309 Nov 2022 pre-release withdrawn -
0.6.0-rc.211 Sep 2022 pre-releaseRelease notes
Open source →Security
-
breaking: Added default limit to how much data
Bytes::from_requestwill consume. Previously it would attempt to consume the entire request body without checking its length. This meant if a malicious peer sent an large (or infinite) request body your server might run out of memory and crash.The default limit is at 2 MB and can be disabled by adding the new
DefaultBodyLimit::disable()middleware. See its documentation for more details.This also applies to these extractors which used
Bytes::from_requestinternally:FormJsonString
(#1346)
Routing
- breaking: Adding a
.route_layeronto aRouterorMethodRouterwithout any routes will now result in a panic. Previously, this just did nothing. #1327
Middleware
- added: Add
middleware::from_fn_with_stateandmiddleware::from_fn_with_state_arcto enable running extractors that require state (#1342)
-
-
0.6.0-rc.123 Aug 2022 pre-releaseRelease notes
Open source →Routing
-
breaking: Nested
Routers will no longer delegate to the outerRouter's fallback. Instead you must explicitly set a fallback on the innerRouter(#1086)This nested router on 0.5:
use axum::{Router, handler::Handler}; let api_routes = Router::new(); let app = Router::new() .nest("/api", api_routes) .fallback(fallback.into_service()); async fn fallback() {}Becomes this in 0.6:
use axum::Router; let api_routes = Router::new() // we have to explicitly set the fallback here // since nested routers no longer delegate to the outer // router's fallback .fallback(fallback); let app = Router::new() .nest("/api", api_routes) .fallback(fallback); async fn fallback() {} -
breaking: The request
/foo/no longer matches/foo/*rest. If you want to match/foo/you have to add a route specifically for that (#1086)For example:
use axum::{Router, routing::get, extract::Path}; let app = Router::new() // this will match `/foo/bar/baz` .route("/foo/*rest", get(handler)) // this will match `/foo/` .route("/foo/", get(handler)) // if you want `/foo` to match you must also add an explicit route for it .route("/foo", get(handler)); async fn handler( // use an `Option` because `/foo/` and `/foo` don't have any path params params: Option<Path<String>>, ) {} -
breaking: Path params for wildcard routes no longer include the prefix
/. e.g./foo.jswill match/*filepathwith a value offoo.js, not/foo.js(#1086)For example:
use axum::{Router, routing::get, extract::Path}; let app = Router::new().route("/foo/*rest", get(handler)); async fn handler( Path(params): Path<String>, ) { // for the request `/foo/bar/baz` the value of `params` will be `bar/baz` // // on 0.5 it would be `/bar/baz` } -
fixed: Routes like
/fooand/*restare no longer considered overlapping./foowill take priority (#1086)For example:
use axum::{Router, routing::get}; let app = Router::new() // this used to not be allowed but now just works .route("/foo/*rest", get(foo)) .route("/foo/bar", get(bar)); async fn foo() {} async fn bar() {} -
breaking: Trailing slash redirects have been removed. Previously if you added a route for
/foo, axum would redirect calls to/foo/to/foo(or vice versa for/foo/). That is no longer supported and such requests will now be sent to the fallback. Consider usingaxum_extra::routing::RouterExt::route_with_tsrif you want the old behavior (#1119)For example:
use axum::{Router, routing::get}; let app = Router::new() // a request to `GET /foo/` will now get `404 Not Found` // whereas in 0.5 axum would redirect to `/foo` // // same goes the other way if you had the route `/foo/` // axum will no longer redirect from `/foo` to `/foo/` .route("/foo", get(handler)); async fn handler() {} -
breaking:
Router::fallbacknow only acceptsHandlers (similarly to whatget,post, etc accept). Use the newRouter::fallback_servicefor setting anyServiceas the fallback (#1155)This fallback on 0.5:
use axum::{Router, handler::Handler}; let app = Router::new().fallback(fallback.into_service()); async fn fallback() {}Becomes this in 0.6
use axum::Router; let app = Router::new().fallback(fallback); async fn fallback() {} -
breaking: Allow
Error: Into<Infallible>forRoute::{layer, route_layer}(#924) -
breaking:
MethodRouternow panics on overlapping routes (#1102) -
breaking:
Router::routenow only acceptsMethodRouters created withget,post, etc. Use the newRouter::route_servicefor routing to anyServices (#1155)
Extractors
-
added: Added new type safe
Stateextractor. This can be used withRouter::with_stateand gives compile errors for missing states, whereasExtensionwould result in runtime errors (#1155)We recommend migrating from
ExtensiontoStatesince that is more type safe and faster. That is done by usingRouter::with_stateandState.This setup in 0.5
use axum::{routing::get, Extension, Router}; let app = Router::new() .route("/", get(handler)) .layer(Extension(AppState {})); async fn handler(Extension(app_state): Extension<AppState>) {} #[derive(Clone)] struct AppState {}Becomes this in 0.6 using
State:use axum::{routing::get, extract::State, Router}; let app = Router::with_state(AppState {}) .route("/", get(handler)); async fn handler(State(app_state): State<AppState>) {} #[derive(Clone)] struct AppState {}If you have multiple extensions you can use fields on
AppStateand implementFromRef:use axum::{extract::{State, FromRef}, routing::get, Router}; let state = AppState { client: HttpClient {}, database: Database {}, }; let app = Router::with_state(state).route("/", get(handler)); async fn handler( State(client): State<HttpClient>, State(database): State<Database>, ) {} #[derive(Clone)] struct AppState { client: HttpClient, database: Database, } #[derive(Clone)] struct HttpClient {} impl FromRef<AppState> for HttpClient { fn from_ref(state: &AppState) -> Self { state.client.clone() } } #[derive(Clone)] struct Database {} impl FromRef<AppState> for Database { fn from_ref(state: &AppState) -> Self { state.database.clone() } } -
breaking: It is now only possible for one extractor per handler to consume the request body. In 0.5 doing so would result in runtime errors but in 0.6 it is a compile error (#1272)
axum enforces this by only allowing the last extractor to consume the request.
For example:
use axum::{Json, http::HeaderMap}; // This won't compile on 0.6 because both `Json` and `String` need to consume // the request body. You can use either `Json` or `String`, but not both. async fn handler_1( json: Json<serde_json::Value>, string: String, ) {} // This won't work either since `Json` is not the last extractor. async fn handler_2( json: Json<serde_json::Value>, headers: HeaderMap, ) {} // This works! async fn handler_3( headers: HeaderMap, json: Json<serde_json::Value>, ) {}This is done by reworking the
FromRequesttrait and introducing a newFromRequestPartstrait.If your extractor needs to consume the request body then you should implement
FromRequest, otherwise implementFromRequestParts.This extractor in 0.5:
struct MyExtractor { /* ... */ } impl<B> FromRequest<B> for MyExtractor where B: Send, { type Rejection = StatusCode; async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> { // ... } }Becomes this in 0.6:
use axum::{ extract::{FromRequest, FromRequestParts}, http::{StatusCode, Request, request::Parts}, }; struct MyExtractor { /* ... */ } // implement `FromRequestParts` if you don't need to consume the request body impl<S> FromRequestParts<S> for MyExtractor where S: Send + Sync, { type Rejection = StatusCode; async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> { // ... } } // implement `FromRequest` if you do need to consume the request body impl<S, B> FromRequest<S, B> for MyExtractor where S: Send + Sync, B: Send + 'static, { type Rejection = StatusCode; async fn from_request(req: Request<B>, state: &S) -> Result<Self, Self::Rejection> { // ... } } -
breaking:
RequestPartshas been removed as part of theFromRequestrework (#1272) -
breaking:
BodyAlreadyExtractedhas been removed (#1272) -
breaking: The following types or traits have a new
Stype param which represents the state (#1155):Router, defaults to()MethodRouter, defaults to()FromRequest, no defaultHandler, no default
-
added: Add
RequestExtandRequestPartsExtwhich adds convenience methods for running extractors tohttp::Requestandhttp::request::Parts(#1301)
Middleware
- breaking: Remove
extractor_middlewarewhich was previously deprecated. Useaxum::middleware::from_extractorinstead (#1077) - added: Support running extractors on
middleware::from_fnfunctions (#1088) - added: Support any middleware response that implements
IntoResponse(#1152) - breaking: Require middleware added with
Handler::layerto haveInfallibleas the error type (#1152)
Misc
- changed: axum's MSRV is now 1.60 (#1239)
- changed: For methods that accept some
S: Service, the bounds have been relaxed so the response type must implementIntoResponserather than being a literalResponse - fixed: Annotate panicking functions with
#[track_caller]so the error message points to where the user added the invalid route, rather than somewhere internally in axum (#1248) - added: Add
ServiceExtwith methods for turning anyServiceinto aMakeServicesimilarly toRouter::into_make_service(#1302)
</details>
-
-
0.5.1720 Oct 2022Nothing published for this version
-
0.5.1610 Sep 2022Release notes
Open source →Security
-
breaking: Added default limit to how much data
Bytes::from_requestwill consume. Previously it would attempt to consume the entire request body without checking its length. This meant if a malicious peer sent an large (or infinite) request body your server might run out of memory and crash.The default limit is at 2 MB and can be disabled by adding the new
DefaultBodyLimit::disable()middleware. See its documentation for more details.This also applies to these extractors which used
Bytes::from_requestinternally:FormJsonString
(#1346)
-
-
0.5.1509 Aug 2022 -
0.5.1425 Jul 2022 withdrawn -
0.5.1315 Jul 2022 -
0.5.1210 Jul 2022Release notes
Open source →- added: Added
debug_handlerwhich is an attribute macro that improves type errors when applied to handler function. It is re-exported fromaxum-macros(#1144)
- added: Added
-
0.5.1102 Jul 2022 -
0.5.1028 Jun 2022 -
0.5.920 Jun 2022Release notes
Open source →- fixed: Fix compile error when the
headersis enabled and theformfeature is disabled (#1107)
- fixed: Fix compile error when the
-
0.5.818 Jun 2022 -
0.5.708 Jun 2022 -
0.5.616 May 2022Release notes
Open source →- added: Add
WebSocket::protocolto return the selected WebSocket subprotocol, if there is one. (#1022) - fixed: Improve error message for
PathRejection::WrongNumberOfParametersto hint at usingPath<(String, String)>orPath<SomeStruct>(#1023) - fixed:
PathRejection::WrongNumberOfParametersnow uses500 Internal Server Errorsince it's a programmer error and not a client error (#1023) - fixed: Fix
InvalidFormContentTypementioning the wrong content type
- added: Add