Skip to content

Commit

Permalink
Document that with_state needs to be last when building a router
Browse files Browse the repository at this point in the history
  • Loading branch information
selfhoster1312 committed Aug 19, 2023
1 parent 52a9039 commit b7c02ee
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
2 changes: 1 addition & 1 deletion axum/src/docs/routing/with_state.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
Provide the state for the router.
Provide the state for the router. This methods needs to be called last when building the router, or your code won't compile.

```rust
use axum::{Router, routing::get, extract::State};
Expand Down
20 changes: 20 additions & 0 deletions axum/src/extract/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,26 @@ use std::{
///
/// [order-of-extractors]: crate::extract#the-order-of-extractors
///
/// Note that `State` should be provided last when building a [`Router`]. This means this code won't compile:
///
/// ```compile_fail
/// # use axum::{Router, routing::get, extract::State};
/// # #[derive(Clone)]
/// # struct AppState {}
/// #
/// # let state = AppState {};
/// #
/// let app = Router::new()
/// // Dont do this! Place `with_state` after `route`, `nest` or `merge`.
/// .with_state(state)
/// .route("/", get(handler));
/// #
/// # async fn handler(State(state): State<AppState>) {}
///
/// // Compilation will fail here
/// let service = app.into_make_service();
/// ```
///
/// ## Combining stateful routers
///
/// Multiple [`Router`]s can be combined with [`Router::nest`] or [`Router::merge`]
Expand Down

0 comments on commit b7c02ee

Please sign in to comment.