Skip to main content

Route Guards

Advanced conditional routing

Actix 4.9+ 6 min read

# Route Guards

Route Guards allow you to dictate whether a request matches a specific route based on more than just the path and method. They can check headers, content types, or even custom logic.

#Built-in Guards

Actix Web provides several built-in guards in the guard module, such as: - guard::Get(), guard::Post() - guard::Header(name, value) - guard::Host(host) - guard::Fn(closure)

#Custom Logic

You can create a custom guard by implementing the actix_web::guard::Guard trait or by using guard::fn_guard.

code_blocksrust
use actix_web::{guard, web, App, HttpResponse};

fn custom_guard(ctx: &guard::GuardContext) -> bool {
    ctx.head().headers().contains_key("x-my-custom-header")
}

// Inside App configuration:
// .route(
//     "/guarded",
//     web::get()
//         .guard(guard::fn_guard(custom_guard))
//         .to(|| async { HttpResponse::Ok().body("Success!") })
// )

Was this page helpful?

Reference Implementation

The following code snippet demonstrates the authoritative pattern for this documentation.

src/main.rs
1use actix_web::{guard, web, App, HttpServer, HttpResponse, Responder};
2
3async fn guarded_handler() -> impl Responder {
4 HttpResponse::Ok().body("You have the secret header!")
5}
6
7#[actix_web::main]
8async fn main() -> std::io::Result<()> {
9 HttpServer::new(|| {
10 App::new().route(
11 "/secret",
12 web::get()
13 .guard(guard::Header("x-secret", "123"))
14 .to(guarded_handler),
15 )
16 })
17 .bind(("127.0.0.1", 8080))?
18 .run()
19 .await
20}
Was this page helpful?