Skip to main content

Headers

Reading HTTP request headers

Actix 4.9+ 5 min read

# Headers

Sometimes you need to inspect HTTP headers directly, such as for custom authentication tokens or client metadata. Actix Web provides multiple ways to access headers.

#Using HttpRequest

The most straightforward way is to extract the HttpRequest object, which contains all the headers.

code_blocksrust
use actix_web::{get, HttpRequest, HttpResponse};

#[get("/headers")]
async fn get_headers(req: HttpRequest) -> HttpResponse {
    if let Some(user_agent) = req.headers().get("User-Agent") {
        HttpResponse::Ok().body(format!("You are using: {:?}", user_agent))
    } else {
        HttpResponse::Ok().body("No user agent found")
    }
}

#Typed Headers Extractor (via actix-web-lab)

For stricter typing, you can use typed header extractors provided by extensions or manually parse header values.

Was this page helpful?

Reference Implementation

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

src/main.rs
1use actix_web::{get, HttpRequest, App, HttpServer, Responder};
2
3#[get("/check")]
4async fn check_header(req: HttpRequest) -> impl Responder {
5 match req.headers().get("X-Custom-Token") {
6 Some(val) => format!("Token: {:?}", val),
7 None => "No token provided".to_string(),
8 }
9}
10
11#[actix_web::main]
12async fn main() -> std::io::Result<()> {
13 HttpServer::new(|| App::new().service(check_header))
14 .bind(("127.0.0.1", 8080))?
15 .run()
16 .await
17}
Was this page helpful?