• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1Apply a [`tower::Layer`] to the router that will only run if the request matches
2a route.
3
4Note that the middleware is only applied to existing routes. So you have to
5first add your routes (and / or fallback) and then call `layer` afterwards. Additional
6routes added after `layer` is called will not have the middleware added.
7
8This works similarly to [`Router::layer`] except the middleware will only run if
9the request matches a route. This is useful for middleware that return early
10(such as authorization) which might otherwise convert a `404 Not Found` into a
11`401 Unauthorized`.
12
13# Example
14
15```rust
16use axum::{
17    routing::get,
18    Router,
19};
20use tower_http::validate_request::ValidateRequestHeaderLayer;
21
22let app = Router::new()
23    .route("/foo", get(|| async {}))
24    .route_layer(ValidateRequestHeaderLayer::bearer("password"));
25
26// `GET /foo` with a valid token will receive `200 OK`
27// `GET /foo` with a invalid token will receive `401 Unauthorized`
28// `GET /not-found` with a invalid token will receive `404 Not Found`
29# async {
30# axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
31# };
32```
33