Custom response headers in Axum

Learn how to add custom HTTP headers to Axum handler responses using tuples, HeaderMap, and Response builder, with examples and common mistakes explained for beginners.

When a web server sends a response back to a browser or client, that response contains not just the body (like HTML or JSON), but also a set of metadata called HTTP headers. Headers describe the response, tell the client how to treat it, and can carry custom information. In Axum, you have several ways to attach custom headers to your responses. This page teaches you all of them, from the simplest one-liner to using the lower-level Response builder.

What HTTP Headers Are

Think of an HTTP response like a physical letter. The body is the letter inside the envelope, and the headers are the information written on the envelope: the sender's address, the date, a "do not bend" notice. Standard headers have a defined meaning - for example, Content-Type tells the browser whether the body is HTML, JSON, or something else. Custom headers are ones you invent for your own purposes, like X-Request-ID or X-Rate-Limit-Remaining. They don't have a predefined meaning for browsers, but your own frontend code, proxies, or other backend services can read them and act on them.

Axum lets you return many types from handlers. Anything that implements the IntoResponse trait can be returned. HeaderMap, tuples containing header arrays, and Response itself all implement IntoResponse. This page focuses specifically on adding custom headers to whatever response you are already building.

Why Add Custom Headers?

Custom headers solve real problems in web applications:

  • Passing metadata from the server to the client (e.g., a request ID for tracing).
  • Implementing CORS (Cross-Origin Resource Sharing) to allow or deny browser requests from other domains.
  • Setting cache-control hints that are specific to your application.
  • Sending authentication tokens or rate-limit information that the frontend needs but shouldn't be in the body.
  • Adding debugging information visible only in the network tab of the browser.

Axum makes it easy to add these headers without building the entire response manually every time. You can mix custom headers with any body or status code.

Your First Custom Header

Let's start with the absolute smallest example. You can return a tuple from your handler where the first element is an array of header name-value pairs, and the second element is the body. The header name can be a string literal, and the value can also be a string literal.

use axum::response::IntoResponse;
async fn handler() -> impl IntoResponse {
    ([("x-custom-header", "hello-from-axum")], "Hello, world!")
}

Here is what happens:

  • ([("x-custom-header", "hello-from-axum")], "Hello, world!") is a tuple.
  • The first part is an array containing one tuple of (&str, &str). Axum knows how to turn that array into response headers.
  • The second part is the string "Hello, world!", which becomes the response body with a 200 OK status.
  • The function uses impl IntoResponse as the return type, which tells Rust "this returns something that can become a response, but I don't want to write the exact type." That's convenient because the exact type would be something like ([(&str, &str); 1], &str).

It works:

If you run this handler and look at the response headers in a browser or with curl, you will see x-custom-header: hello-from-axum along with the default headers Axum sends.

Adding Multiple Custom Headers

You can put as many header pairs as you like inside the array. Each one becomes a separate header on the response.

use axum::response::IntoResponse;
async fn handler() -> impl IntoResponse {
    (
        [
            ("x-request-id", "abc-123"),
            ("x-server-name", "axum-beginner"),
            ("x-api-version", "1.0"),
        ],
        "Here is your data",
    )
}

The array can contain any number of (&str, &str) pairs. Note that all header names and values are written as string literals. They must be valid header names and values according to the HTTP specification; more on that later.

Using HeaderMap for More Control

Sometimes you want to build headers dynamically, perhaps based on some condition, or you already have a HeaderMap from another part of your code. Axum accepts a HeaderMap directly as the first element of a tuple.

use axum::http::{header, HeaderMap, HeaderValue};
use axum::response::IntoResponse;
async fn handler() -> impl IntoResponse {
    let mut headers = HeaderMap::new();
    headers.insert(header::SERVER, HeaderValue::from_static("axum-server"));
    headers.insert("x-custom-header", HeaderValue::from_static("custom-value"));
    headers.insert("x-request-id", HeaderValue::from_static("req-42"));
    (headers, "Hello with a HeaderMap")
}

In this example:

  • We create a new empty HeaderMap.
  • header::SERVER is a constant for the standard Server header. We use HeaderValue::from_static because we know the value never changes.
  • The second insert call uses a string "x-custom-header". The HeaderMap::insert method converts the &str into a HeaderName at runtime, and it panics if the name is not valid, so prefer a constant from header whenever one exists. HeaderValue::from_static is for values, not names: it panics at runtime if the value contains characters that are not allowed in a header value.
  • The tuple (headers, "Hello with a HeaderMap") returns the HeaderMap as the header part and the string as the body.

The advantage of HeaderMap is that you can build it programmatically, add or remove headers based on logic, and reuse it across handlers.

Building the Whole Response with Response::builder

If you need full control over status code, headers, and body, you can use the Response::builder API. Here we add custom headers with the .header() method.

use axum::body::Body;
use axum::http::StatusCode;
use axum::response::Response;
async fn handler() -> Response {
    Response::builder()
        .status(StatusCode::OK)
        .header("x-custom-header", "value-from-builder")
        .header("x-another-header", "another-value")
        .body(Body::from("Built with Response::builder"))
        .unwrap()
}

Each .header() call adds one header. You can chain as many as you like. The .unwrap() at the end is necessary because builder.body() returns a Result<Response, Error>. In this example the body and headers are fixed string literals that are known to be valid, so unwrap() cannot fail here. When a header value comes from user input or another place that might be invalid, do not unwrap: return the error as a response instead, for example by returning Result<Response, StatusCode> and converting the builder error into a 500 status with .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?.

The difference from the tuple approach is that here you explicitly set the status and the body type (Body::from). The tuple approach implicitly gives you 200 OK and a string body. Both produce a valid response; choose whichever fits your needs.

Combining Status Code, Headers, and Body in a Tuple

You often need to return a non-200 status code together with custom headers. Axum lets you combine a status code, a header array (or HeaderMap), and a body in one tuple.

use axum::http::StatusCode;
use axum::response::IntoResponse;
async fn handler() -> impl IntoResponse {
    (
        StatusCode::CREATED,
        [("x-created-resource", "/users/42")],
        "User created successfully",
    )
}

This returns a 201 Created status, sets the custom header x-created-resource, and sends the body. The order matters: status first, then headers, then body.

You can also use a HeaderMap instead of the array:

use axum::http::{header, HeaderMap, StatusCode};
use axum::response::IntoResponse;
async fn handler() -> impl IntoResponse {
    let mut headers = HeaderMap::new();
    headers.insert("x-custom-header", "custom-value".parse().unwrap());
    (StatusCode::ACCEPTED, headers, "Processing")
}

This returns 202 Accepted with the custom header.

Using impl IntoResponse to Avoid Long Type Signatures

As you saw, the exact return type of a handler that returns a tuple with headers can be long. For example, without impl IntoResponse, you would have to write:

async fn handler() -> (StatusCode, [(&'static str, &'static str); 1], &'static str) {
    (StatusCode::OK, [("x-foo", "bar")], "Hello")
}

The type [(&'static str, &'static str); 1] is verbose. Writing impl IntoResponse hides that complexity. It tells Rust "the return type implements IntoResponse, but I don't want to spell it out." This works only if your handler returns exactly one concrete type. If you return different types in different branches of an if expression, impl IntoResponse won't compile. In that case, you must convert everything to a common type like axum::response::Response or use a concrete error type with Result. For simple handlers that always return the same shape, impl IntoResponse is convenient and readable.

Header Naming Rules and Best Practices

Header names must follow the HTTP token grammar. That means they can contain letters, digits, and a few symbols like hyphen and underscore, but they cannot contain spaces, control characters, or most punctuation. Axum (and the underlying http crate) will reject invalid names with an error at runtime if you try to insert them into a HeaderMap using a string that fails parsing.

For custom headers, it was long conventional to prefix them with X-, like X-Custom-Header. That convention comes from the early days of the web. While the prefix is no longer officially recommended, it remains widely used and immediately signals "this is a custom header." Many libraries and frameworks still expect such headers. You are free to use any valid name, but consistency helps. Choose names that describe the data, are unlikely to clash with standard headers, and are documented for your team.

Case sensitivity:

Header names are case-insensitive in HTTP. x-custom-header, X-Custom-Header, and X-CUSTOM-HEADER all refer to the same header. Axum normalizes them internally, so you don't have to worry about exact case. But when reading headers back (for example, in middleware or extractors), use the same name consistently.

Common Mistakes and How to Avoid Them

Let's look at mistakes beginners often make when adding custom headers.

Forgetting the Body

A HeaderMap alone implements IntoResponse and will produce a response with empty body and default status 200 OK. That may be what you want for a simple notification, but if you intended to send data, you must include a body in the tuple.

use axum::http::HeaderMap;
// This returns an empty body, no text
async fn wrong() -> HeaderMap {
    let mut headers = HeaderMap::new();
    headers.insert("x-custom", "value".parse().unwrap());
    headers
}

If you wanted the body "Hello", you need to return (headers, "Hello").

Empty response mistake:

A handler returning only a HeaderMap will not send any content in the response body. The client will see an empty response. Always check whether you meant to include a body.

Invalid Header Value

Header values also have rules. They cannot contain certain control characters, and some characters may require special handling. HeaderValue::from_static will panic if the value is invalid, and .parse().unwrap() will panic as well. Use HeaderValue::from_str and handle the Result properly if the value might come from user input.

use axum::http::HeaderValue;
// This panics at runtime because a newline is not allowed in a header value
fn make_value() -> HeaderValue {
    HeaderValue::from_static("hello\nworld")
}

Runtime panic:

If you use HeaderValue::from_static or .parse().unwrap() with an invalid value, your program will panic at runtime. Always ensure the value is valid, or use HeaderValue::from_str which returns a Result you can handle.

Forgetting to Import Required Types

To use HeaderMap, HeaderValue, or header constants, you need to import them from axum::http. If you only write use axum::response::IntoResponse;, the compiler will complain about missing types.

use axum::http::{header, HeaderMap, HeaderValue};

With that import in place, HeaderMap, HeaderValue, and the header constants are all available to the handler, and the compiler stops complaining.

Mixing String and HeaderName

You can insert into a HeaderMap using either a string literal or a HeaderName. The string must be parsed into a HeaderName at runtime, which can fail. For known, fixed header names, consider using constants from axum::http::header (like header::SERVER) or define your own HeaderName constants once. That avoids runtime parsing and gives compile-time safety.

use axum::http::{header::HeaderName, HeaderMap};
use axum::response::IntoResponse;
static X_CUSTOM: HeaderName = HeaderName::from_static("x-custom");
async fn handler() -> impl IntoResponse {
    let mut headers = HeaderMap::new();
    headers.insert(X_CUSTOM.clone(), "value".parse().unwrap());
    (headers, "body")
}

The .clone() after X_CUSTOM is required, not optional. HeaderName is not a type you can copy, and a static value cannot be moved out of its storage, so passing X_CUSTOM directly fails to compile with "cannot move out of static item". Cloning gives insert its own owned copy while the static stays in place for the next request.

Practical Examples

Let's explore a few real-world scenarios where custom headers shine.

Request ID for Tracing

When a request comes in, you might generate a unique identifier and attach it to the response so the client can report it back if something goes wrong. This example uses the uuid crate to generate the identifier. Add it to Cargo.toml first:

[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
uuid = { version = "1", features = ["v4"] }

Then use a HeaderMap to carry the generated value:

use axum::http::{HeaderMap, HeaderValue};
use axum::response::IntoResponse;
async fn handler() -> impl IntoResponse {
    let request_id = uuid::Uuid::new_v4().to_string();
    let body = "Data processed";
    let mut headers = HeaderMap::new();
    headers.insert(
        "x-request-id",
        HeaderValue::from_str(&request_id).unwrap(),
    );
    (headers, body)
}

The HeaderMap matters here. The identifier is a String created inside the handler, and the response must outlive the handler call, so the handler cannot return a borrowed &str that points at that local String. HeaderValue::from_str copies the text into an owned header value, which is safe to return. The unwrap() after from_str is safe in this exact case because a freshly generated UUID contains only hex digits and hyphens, which are always valid in a header value. A shortcut that looks tempting, ([("x-request-id", request_id.as_str())], body), does not compile: the compiler rejects it because the returned tuple would borrow the local variable. When a header value is built at runtime from a local String, always put it into a HeaderMap with HeaderValue::from_str instead of borrowing it in an array.

CORS Headers

If your frontend is served from http://localhost:3000 but your API is on http://localhost:8080, the browser will block cross-origin requests unless the server includes CORS headers. A minimal manual approach is:

use axum::response::IntoResponse;
async fn handler() -> impl IntoResponse {
    (
        [
            ("Access-Control-Allow-Origin", "http://localhost:3000"),
            ("Access-Control-Allow-Methods", "GET, POST, OPTIONS"),
            ("Access-Control-Allow-Headers", "Content-Type, Authorization"),
        ],
        "CORS-enabled response",
    )
}

This is not the full CORS implementation, but it shows the concept. For production, you would typically use a middleware layer like tower-http's CorsLayer, but knowing how to set these headers manually helps you understand what's happening.

Cache-Control for Dynamic Content

You might want to tell the browser not to cache a particular response, or to cache it for a short time. That's done with the Cache-Control header.

use axum::http::HeaderValue;
use axum::response::IntoResponse;
use axum::http::header::CACHE_CONTROL;
async fn handler() -> impl IntoResponse {
    let mut headers = axum::http::HeaderMap::new();
    headers.insert(CACHE_CONTROL, HeaderValue::from_static("no-store"));
    (headers, "Sensitive data - do not cache")
}

no-store tells the browser and any proxies not to store this response at all.

Summary

Custom response headers give your Axum handlers a way to communicate extra information to clients without putting it in the response body. You can add them using a tuple with an array of (name, value) pairs, using a HeaderMap, or by building the entire Response with Response::builder. Each method has its place: arrays are great for quick, static headers; HeaderMap allows dynamic construction; Response::builder gives you full control over status, headers, and body.

The most important thing to remember is that header names and values must be valid HTTP tokens. Use HeaderValue::from_static or HeaderValue::from_str to avoid panics, and be careful not to forget the response body when using HeaderMap alone. With these tools, you can implement request IDs, CORS, custom caching, and many other features in a clean and maintainable way.