Seeking guidance on middleware stack usage before routing in Axum #3202
Replies: 1 comment
-
Bit more details about the two approaches you came up with (on which I commend you by the way, I don't think I'd come up with the What .layer(tower::layer::layer_fn(|inner|
ServiceBuilder::new()
.layer_fn(tower::util::BoxCloneSyncService::new)
.map_response(axum::response::IntoResponse::into_response)
.service(inner)
)) where the But you could change the let make = ServiceExt::<axum::extract::Request>::into_make_service(service);
// let make = ServiceExt::into_make_service(service); // <- doesn't work, we need the type hint
axum::serve(listener, make).await.unwrap(); When you give the explicit type, the request mapping is not needed anymore. As for the response mapping, I don't think you can really get around that right now because |
Beta Was this translation helpful? Give feedback.
-
Summary
Description
I'm trying to ensure certain middlewares (e.g. rewriting uri, logging, CORS) always run before Axum's router attempts to match incoming requests. The main reason is that if routing fails (no matching path), the request is immediately returned with an error response, and none of my desired middlewares get a chance to run.
However, I'm running into a couple of issues around the type system when stacking middlewares:
TraceLayer
,CompressionLayer
, or custom rewriting, I run into compilation errors about mismatched service types.axum::middleware::from_fn
), or.map_request_body(axum::body::Body::new)
&.map_response_body(axum::body::Body::new)
.In both cases, these solutions feel a bit awkward or heavy-handed. I'm not completely sure if I'm misusing Axum’s or Tower's layering system, or whether these “workarounds” might have unexpected runtime consequences.
Below is a simplified excerpt from my code:
If I omit the calls to map_request_body & map_response_body, the compiler complains that the final service type doesn’t match what Axum expects. Alternatively, I can prepend an empty from_fn middleware that simply does next.run(req).await, and that also makes the type errors go away—again, feels unintuitive.
Questions
I’d really appreciate any best-practice recommendations or clarifications on how Axum 0.8.x is intended to handle these kinds of global pre-routing middlewares in a more idiomatic way. Thank you in advance!
axum version
0.8.1
Beta Was this translation helpful? Give feedback.
All reactions