Search code examples
rustbackendrust-axum

Rust Axum Access state in nested router


I'm trying to access the state pool passed from the parent router to the child router, here is the main router in main.rs:

let app = Router::new()
    .nest("/products", create_products_router())
    .nest("/auth", create_auth_router())
    .with_state(pool)
    .layer(
        CorsLayer::new()
            .allow_origin("http://localhost:4200".parse::<HeaderValue>().unwrap())
            .allow_methods([Method::GET, Method::POST, Method::DELETE, Method::PUT])
            .allow_headers(vec!["content-type".parse().unwrap()]),
    );

Here is the create_auth_router():

    pub fn create_auth_router() -> Router<PgPool> {
    Router::new()
        .route("/login", post(login))
        .route("/register", post(register))
        .route(
            "/profile",
            get(profile).layer(middleware::from_fn_with_state(
                How to access state "pool" here!!!,
                authorization_middleware,
            )),
        )
}

Solution

  • Currently, the only way to access state in middleware is with middleware::from_fn_with_state, which requires it to be provided upfront - separately from how the router provides the state to handlers.

    Your create_auth_router does not have the state to provide to it, so you'll have to change it:

    pub fn create_auth_router(state: PgPool) -> Router<PgPool> {
        // ...
    }
    
    let app = Router::new()
        .nest("/products", create_products_router())
        .nest("/auth", create_auth_router(pool.clone()))
        .with_state(pool)
        // ...