Skip to main content

Custom Headers

Setting HTTP headers on responses

Actix 4.9+ 5 min read

# Custom Headers

You often need to attach headers to responses, such as cache controls, custom identifiers, or cookies.

#Modifying the Response

Use the insert_header or append_header methods on the HttpResponseBuilder.

code_blocksrust
use actix_web::{get, HttpResponse, Responder};
use actix_web::http::header;

#[get("/data")]
async fn get_data() -> impl Responder {
    HttpResponse::Ok()
        .insert_header((header::CACHE_CONTROL, "public, max-age=3600"))
        .insert_header(("X-Custom-Identifier", "12345"))
        .body("Cached data")
}

#typed Headers

Actix Web leverages the http::header module for strongly typed standard header names, reducing the risk of typos compared to string literals.

Was this page helpful?

Reference Implementation

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

src/main.rs
1use actix_web::{get, App, HttpServer, HttpResponse, Responder};
2
3#[get("/headers")]
4async fn custom_headers() -> impl Responder {
5 HttpResponse::Ok()
6 .insert_header(("X-RateLimit-Limit", "100"))
7 .body("Header set")
8}
9
10#[actix_web::main]
11async fn main() -> std::io::Result<()> {
12 HttpServer::new(|| App::new().service(custom_headers))
13 .bind(("127.0.0.1", 8080))?
14 .run()
15 .await
16}
Was this page helpful?