[Axum] from_fn_with_state does not compile

⚓ rust    📅 2025-05-18    👤 surdeus    👁️ 4      

surdeus

Warning

This post was published 43 days ago. The information described in this article may have changed.

Hi,
Picked up the guide from here:

I want to understand why this does not work the way it has been described in the page:

My middleware

pub async fn middleware(
    State(state): State<AppState>,
    session: Session,
    mut request: Request,
    next: Next,
) -> Response {
   /* do something */
    next.run(request).await
}

my usage:

.layer(axum::middleware::from_fn_with_state(
    shared_state.clone(),
    middleware
))

AppState:

struct AppState {
    snippets: Model
}
#[derive(Clone)]
pub struct Model {
    pool: Pool<MySql>,
}

The error I get:
error[E0277]: the trait bound axum::middleware::FromFn<fn(State<AppState>, tower_sessions::Session, axum::http::Request<Body>, Next) -> impl Future<Output = Response<Body>> {authenticate}, Arc<AppState>, Route, _>: tower_service::Service<axum::http::Request<Body>> is not satisfied
--> src/routes.rs:60:20
|
60 | .layer(axum::middleware::from_fn_with_state(
| __-----^
| | |
| | required by a bound introduced by this call
61 | | shared_state.clone(),
62 | | authenticate,
63 | | )) // since this uses session it needs to be work after the session layer
| |
^ unsatisfied trait bound
|
= help: the trait tower_service::Service<axum::http::Request<Body>> is not implemented for FromFn<fn(..., ..., ..., ...) -> ... {authenticate}, ..., ..., ...>
= help: the following other types implement trait tower_service::Service<Request>:
axum::middleware::FromFn<F, S, I, (T1, T2)>
axum::middleware::FromFn<F, S, I, (T1, T2, T3)>
axum::middleware::FromFn<F, S, I, (T1, T2, T3, T4)>
axum::middleware::FromFn<F, S, I, (T1, T2, T3, T4, T5)>
axum::middleware::FromFn<F, S, I, (T1, T2, T3, T4, T5, T6)>
axum::middleware::FromFn<F, S, I, (T1, T2, T3, T4, T5, T6, T7)>
axum::middleware::FromFn<F, S, I, (T1, T2, T3, T4, T5, T6, T7, T8)>
axum::middleware::FromFn<F, S, I, (T1, T2, T3, T4, T5, T6, T7, T8, T9)>
and 8 others
note: required by a bound in Router::<S>::layer

4 posts - 2 participants

Read full topic

🏷️ rust_feed