SetRequestHeader Layer in Axum
Learn tower-http SetRequestHeaderLayer in axum, its three modes overriding appending and if_not_present, fixed values versus closures computed from the request, and its response-side twin
What setting a request header means
A header is a name and value pair attached to an HTTP request, separate from the body. The client sends headers such as the address it wants and the kind of response it accepts. The server reads them to decide what to do. A request header layer writes a header onto the request before the handler sees it, so the handler finds a header the client may never have sent.
The layer is for values the server decides. A tenant name the server assigns from its own configuration. A default mode for clients that did not pick one. A version stamp that marks every request as belonging to a particular deployment. The handler then reads one header and trusts it, instead of repeating the same decision in every handler.
This page covers three decisions about that header. Which mode sets it, and who wins when the client already sent the same header. Where the value comes from, a fixed value written in the code or a value computed from the request itself. And which direction the header travels, because the same idea exists for responses too.
Setting up the project
Every example on this page runs in the same small project. Create it with cargo new set-header-demo and replace the generated Cargo.toml with this one.
[package]
name = "set-header-demo"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
tower = { version = "0.5", features = ["util"] }
tower-http = { version = "0.7", features = ["set-header", "util"] }
The versions here are axum 0.8.9, tokio 1.54.1, tower 0.5.3, and tower-http 0.7.1. The tower-http feature set-header turns on the module this page teaches. The util feature turns on the one-line builder methods shown near the end of the page. The tower feature util turns on ServiceBuilder.
Without the set-header feature the module does not exist:
If the import tower_http::set_header::... fails with an unresolved import error, the cause is almost always a missing feature flag, not a typo. Add "set-header" to the tower-http features in Cargo.toml. The one-line builder methods additionally need the util feature.
The smallest working example
One layer, one header, one handler that reports what it received. The layer forces the header x-tenant to the value acme on every request, whatever the client sent.
use axum::{
extract::Request,
http::{HeaderName, HeaderValue},
routing::get,
Router,
};
use tower_http::set_header::SetRequestHeaderLayer;
async fn echo_tenant(req: Request) -> String {
req.headers()
.get("x-tenant")
.map(|v| v.to_str().unwrap().to_string())
.unwrap_or_else(|| "<missing>".to_string())
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(echo_tenant))
.layer(SetRequestHeaderLayer::overriding(
HeaderName::from_static("x-tenant"),
HeaderValue::from_static("acme"),
));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
The handler takes the whole Request as its argument and reads the x-tenant header from it. Request here is axum's request type, the full incoming request with its headers, its body, and its extensions. The handler answers with the header value, or with the words <missing> when the header is absent, so a single curl request shows exactly what the handler saw.
The layer is built with SetRequestHeaderLayer::overriding. The first argument is the header name, built with HeaderName::from_static, which makes a header name from a string written directly in the code. The second argument is the value, built with HeaderValue::from_static, which makes a header value from a string literal. overriding is one of three modes, and it means the server value replaces whatever the client sent.
Send a request that tries to set its own tenant:
$ curl -s -H "x-tenant: evil" http://localhost:3000/
acme
The client sent evil and the handler saw acme. The layer replaced the client value before the handler ran. Send a request with no tenant header at all and the answer is the same, because the layer sets the value whether or not the client sent one. That is the whole behaviour of overriding in one line: the server value always wins.
The three modes
One layer, three constructors. They differ only in what happens when the client already sent the header.
overriding replaces the client value. The server value always wins. appending keeps the client value and adds the server value alongside it, so the request ends up with two values for the same header name. if_not_present sets the server value only when the client sent nothing. The client value always wins.
The difference is easiest to see with all three running at once, probed by a handler that reports what it received. This program stacks four layers: one overriding layer for a tenant, two appending layers for a multi-value header, and one if_not_present layer for a mode with a default.
use axum::{
extract::Request,
http::{HeaderName, HeaderValue},
routing::get,
Router,
};
use tower_http::set_header::SetRequestHeaderLayer;
async fn echo_headers(req: Request) -> String {
let h = req.headers();
let get = |n: &str| {
h.get(n)
.map(|v| v.to_str().unwrap().to_string())
.unwrap_or_else(|| "<missing>".to_string())
};
let all: Vec<String> = h
.get_all("x-multi")
.iter()
.map(|v| v.to_str().unwrap().to_string())
.collect();
format!(
"tenant={} mode={} multi=[{}]",
get("x-tenant"),
get("x-mode"),
all.join(",")
)
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(echo_headers))
.layer(SetRequestHeaderLayer::overriding(
HeaderName::from_static("x-tenant"),
HeaderValue::from_static("acme"),
))
.layer(SetRequestHeaderLayer::appending(
HeaderName::from_static("x-multi"),
HeaderValue::from_static("one"),
))
.layer(SetRequestHeaderLayer::appending(
HeaderName::from_static("x-multi"),
HeaderValue::from_static("two"),
))
.layer(SetRequestHeaderLayer::if_not_present(
HeaderName::from_static("x-mode"),
HeaderValue::from_static("default-mode"),
));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
The handler uses two different reads. .get(name) returns the first value for a header, which is enough for x-tenant and x-mode, because those headers hold one value each. .get_all(name) returns every value for a header, which is what x-multi needs, because appending can put several values under one name. The handler joins them with commas inside square brackets, so the output shows the full list in order.
Send a request with a tenant and a mode:
$ curl -s -H "x-tenant: evil" -H "x-mode: client-mode" http://localhost:3000/
tenant=acme mode=client-mode multi=[two,one]
Three results in one line. The tenant is acme, because overriding replaced the client's evil. The mode is client-mode, because if_not_present left the client's value alone. The multi-value header holds [two,one], both appended values, and the order carries a lesson of its own. The layers are chained .layer() calls, and in a chain the last layer added is outermost and runs first. The two layer was added after the one layer, so it runs first and appends two before one is appended. With a ServiceBuilder the order would follow the listing order instead, first listed running first.
Send the same request with no headers at all:
$ curl -s http://localhost:3000/
tenant=acme mode=default-mode multi=[two,one]
Now if_not_present has inserted its default, because the client sent nothing. The other two modes behave the same as before. overriding always sets, and appending always adds.
One more probe shows what appending does to a value the client sent. A request carrying its own x-multi value reaches the handler with all three values, client value first:
$ curl -s -H "x-multi: client-val" http://localhost:3000/
tenant=acme mode=default-mode multi=[client-val,two,one]
Appending never removes anything. The client value stays, and the two server values join it. A handler that reads this header with .get() sees only the first value, client-val, and misses the rest. A handler that needs the full list must use .get_all().
Choosing a mode is choosing who wins:
Overriding means the server wins. if_not_present means the client wins. Appending means nobody wins, because both values travel together and the code that reads the header must handle a list. For a tenant or a default, that choice is the whole design decision. Pick it deliberately, and write it down next to the layer, because a reader who cannot tell who wins cannot tell whether the code is safe.
Which mode for which header
The mode choice is usually obvious once you name what the header is for.
| Header | Mode | Why |
|---|---|---|
Tenant, region, or shard (x-tenant) | overriding | The server decides, and a client-sent value must not be able to impersonate another tenant |
A default the client may override (x-mode, a locale, a feature flag) | if_not_present | The client choice wins, and the server only fills the gap |
| A version stamp or marker the handler needs | overriding | One authoritative value, so the handler never has to guess which one counts |
Multi-valued headers (Vary, Cache-Control directives) | appending | The header is genuinely a list, and each layer contributes an entry |
| A header derived from the request, copied into a canonical name | overriding with a closure | The server normalises the request before the handler sees it |
The dangerous row is the first one. A tenant header set with if_not_present lets any client choose its own tenant by sending the header. That is a privilege-escalation bug dressed as a default: a client that sends x-tenant: victim-company reads another tenant's data. If a header controls access, authorisation, or routing to another tenant's data, it is overriding, always. Defaults are for preferences, never for identity.
The other common mistake runs the other way. A default set with overriding silently ignores every client that tries to choose. A client that sends a locale of fr and always gets the server default of en has no way to know its choice was discarded, because the response gives no hint. When the client choice is legitimate, if_not_present is the mode that respects it.
Never use ifnotpresent for identity:
A tenant, a user id, a role, or any header that decides whose data a request touches must be set with overriding. With if_not_present, the client picks the value, and picking someone else's value is one header away. This mistake compiles, passes every test that does not send the header, and fails in production the first time a client tries.
Fixed values versus closures
The value argument is not just a HeaderValue. It is anything implementing MakeHeaderValue, a trait with one method that produces a header value from a message. For a request header layer, the message is the request itself.
pub trait MakeHeaderValue<T> {
fn make_header_value(&mut self, message: &T) -> Option<HeaderValue>;
}
The trait is implemented for three kinds of value. A plain HeaderValue always returns itself. An Option<HeaderValue> returns the value when it is Some and nothing when it is None. And any closure that takes a reference to the request and returns an Option<HeaderValue> counts too, which turns the layer into a small function over the request: derive one header from another, compute a value from the path, or decide not to set the header at all by returning None.
The closure form copies a hint header into a canonical name. A client sends x-tenant-hint, and the server normalises it into x-tenant before the handler runs:
use axum::{extract::Request, routing::get, Router};
use tower_http::set_header::SetRequestHeaderLayer;
let app = Router::new()
.route("/", get(echo_tenant))
.layer(SetRequestHeaderLayer::overriding(
HeaderName::from_static("x-tenant"),
|req: &Request| req.headers().get("x-tenant-hint").cloned(),
));
The closure receives a reference to the request, looks up the hint header, and clones its value. .cloned() turns the borrowed header value into an owned one, because the layer needs to own the value it inserts. A request carrying x-tenant-hint: hinted-tenant reaches the handler with x-tenant: hinted-tenant. A request with no hint reaches the handler with no x-tenant at all, because the closure returned None, and None means do not set the header. Both cases were run against a live server: the first answered hinted-tenant, the second answered <missing>.
The closure sees the whole request, so the derivation can use anything on it, not just headers. A common variant derives a value from the path: an API version from the first path segment, a region from a path prefix, a tenant from a route shaped like /t/{name}/.... The shape is identical, a closure over &Request returning Option<HeaderValue>, and the same None rule applies. When the path does not match the expected shape, return None and set nothing, rather than inventing a value. One caution: the closure sees the raw request URI, but it cannot know which route matched. Derive from the URI string itself, never from an assumption about the matched route.
The closure runs synchronously on every request, which means it runs in the same step as the rest of the request handling, with no waiting for anything else. It must not block. A closure that waits on a lock or a network call stalls the request. Anything heavier belongs in middleware that can wait, such as a function-based middleware or a request mapper. The rule is simple: if the value is a function of the request itself, use this layer. If it needs anything else, use something else.
A closure that returns None sets nothing:
None from a closure, or from an Option<HeaderValue>, is not an error and not an empty header. It means the layer skips the header entirely, and the handler sees the request as if the layer did not exist. When a handler reports a missing header, check whether the closure returned None for that request before assuming the layer is broken.
Fixed values, optional values, and invalid values
The value argument has three forms, because MakeHeaderValue is implemented for three types. A plain HeaderValue always sets. A closure computes per request, as above. And an Option<HeaderValue> sets the header when it is Some and never sets it when it is None, the fixed equivalent of the closure None.
The handler for this example reads the version header the same way the tenant handler read its header:
async fn echo_version(req: Request) -> String {
req.headers()
.get("x-version")
.map(|v| v.to_str().unwrap().to_string())
.unwrap_or_else(|| "<missing>".to_string())
}
// The header is set only when the configuration provides a value.
let config_version: Option<&str> = Some("1.2.3");
let maybe_version: Option<HeaderValue> =
config_version.map(|v| v.parse().unwrap());
let app = Router::new()
.route("/", get(echo_version))
.layer(SetRequestHeaderLayer::if_not_present(
HeaderName::from_static("x-version"),
maybe_version,
));
That form is for values that come from configuration: a version string that may be absent in a development build, a deployment stamp that only exists in production. The layer needs no branch around it. The Option is the branch. Run with the configuration present, the handler sees 1.2.3. Run with it set to None, the handler sees <missing>. Both cases were verified against a live server.
One more validity rule, shared by all three forms: header values must be valid. HeaderValue::from_static panics on bytes that are not allowed in a header value, control characters for example. HeaderValue::from_str and .parse() return an error instead of panicking. Values that come from user input or configuration should go through the fallible form and be validated or rejected at startup. A panic in a layer constructor is loud and early, which is the good outcome. Prefer literals and validated configuration for header values, and treat a panic from from_static as a typo to fix, not a mystery to work around. The same rule applies to header names: HeaderName::from_static panics on an invalid name, such as one with uppercase letters or spaces, so a typo fails fast at startup rather than silently at runtime.
The response side, SetResponseHeaderLayer
The same three modes exist for responses, as SetResponseHeaderLayer. The classic use is a version stamp: every response carries the build version, whatever the handler returns.
use axum::{http::{HeaderName, HeaderValue}, routing::get, Router};
use tower_http::set_header::SetResponseHeaderLayer;
let app = Router::new()
.route("/", get(|| async { "ok" }))
.layer(SetResponseHeaderLayer::overriding(
HeaderName::from_static("x-version"),
HeaderValue::from_static("1.2.3"),
));
Every response now carries x-version: 1.2.3. The mode choice matters here too. overriding replaces a version a handler set itself. if_not_present lets a handler override the default for its own responses. appending produces a multi-value header that most clients will not expect. For a version stamp, overriding or if_not_present is the sane choice. Appending is for headers that are genuinely multi-valued, like Vary or Cache-Control directives.
The response twin also accepts a closure, and the closure receives the response instead of the request, so the value can be derived from what the handler produced. This layer echoes the response status back as a header:
use axum::{http::HeaderName, response::Response, routing::get, Router};
use tower_http::set_header::SetResponseHeaderLayer;
let app = Router::new()
.route("/", get(|| async { "ok" }))
.layer(SetResponseHeaderLayer::overriding(
HeaderName::from_static("x-status-echo"),
|res: &Response<axum::body::Body>| {
Some(res.status().as_str().parse().unwrap())
},
));
A request to this route comes back with x-status-echo: 200, because the handler returned a 200 status and the closure turned that status into the header value. The closure type is &Response<Body>, the response with axum body type, and the value forms are the same as on the request side: a fixed HeaderValue, an Option<HeaderValue>, or a closure returning Option<HeaderValue>, with None meaning do not set the header. The response layer is not this page's subject, so it gets this one section and no more. The request side above is where the three modes, the closures, and the optional values are taught, and they behave the same way on the response side.
How to tell the response stamp is working:
Send any request to a route wrapped by the response layer and read the response headers. If x-version: 1.2.3 is present on every response, including responses from handlers that never mention a version, the layer is running. If it is present on some routes and missing on others, the layer is attached to one route instead of the whole router.
Setting several headers at once
When several headers all need the same mode, one layer per header is verbose. The multi-header layer sets a list of headers in one layer, all under one mode. Each entry is a name and value pair, written as a tuple and converted with .into().
use axum::{
extract::Request,
http::{HeaderName, HeaderValue},
routing::get,
Router,
};
use tower_http::set_header::request::SetMultipleRequestHeadersLayer;
let app = Router::new()
.route("/", get(echo_headers))
.layer(SetMultipleRequestHeadersLayer::overriding(vec![
(
HeaderName::from_static("x-tenant"),
HeaderValue::from_static("acme"),
)
.into(),
(
HeaderName::from_static("x-mode"),
HeaderValue::from_static("default-mode"),
)
.into(),
]));
A request with x-tenant: evil reaches the handler as tenant=acme mode=default-mode multi=[]. Both headers were set by the one layer, under the one mode, overriding. The multi list is empty here because this program sets no x-multi header at all, and the handler still prints the empty list, which is the honest output for a header nobody set. The same three modes exist here: overriding, appending, and if_not_present, each taking the same list. The trade-off is that every header in the list shares the mode. When two headers need different modes, use two single-header layers instead, or one multi-header layer plus one single-header layer. The multi-header layer is a shorthand for the common case, not a replacement for the single-header layer.
Combining modes in one stack
Real stacks combine the modes and the directions. A typical combination is a forced tenant, a default mode, and a version stamp on the response, in one builder with three layers:
use axum::{
extract::Request,
http::{HeaderName, HeaderValue},
routing::get,
Router,
};
use tower::ServiceBuilder;
use tower_http::set_header::{SetRequestHeaderLayer, SetResponseHeaderLayer};
let app = Router::new()
.route("/", get(echo_headers))
.layer(
ServiceBuilder::new()
.layer(SetRequestHeaderLayer::overriding(
HeaderName::from_static("x-tenant"),
HeaderValue::from_static("acme"),
))
.layer(SetRequestHeaderLayer::if_not_present(
HeaderName::from_static("x-mode"),
HeaderValue::from_static("default-mode"),
))
.layer(SetResponseHeaderLayer::overriding(
HeaderName::from_static("x-version"),
HeaderValue::from_static("1.2.3"),
)),
);
A request with x-tenant: evil and x-mode: client-mode reaches the handler as tenant=acme mode=client-mode multi=[], and the response carries x-version: 1.2.3. That output was verified against a live server. The multi list is empty because no layer in this stack sets x-multi, and the handler prints the empty list rather than hiding the header it did not receive. Each layer is independent. The request layers compose with each other exactly as they did as chained .layer() calls, and the response layer runs on the way out without interfering.
Two details matter when combining. First, ordering between two request-header layers only matters when they touch the same header, or when appending order matters, as shown in the three-modes section. Layers for different headers commute, which means their order changes nothing. Second, the layers in a ServiceBuilder run in listing order, while chained .layer() calls run in reverse, last added first. A stack written both ways must be checked against the order rule for the form it is written in, not against the other form.
The one-line form
The builder methods from the ServiceBuilderExt trait collapse each layer into one method call. The request methods are override_request_header, append_request_header, and insert_request_header_if_not_present, and the same three exist for responses. They are exactly the layers above, same modes, same behaviour, for stacks already written as a builder.
use axum::http::{HeaderName, HeaderValue};
use tower::ServiceBuilder;
use tower_http::ServiceBuilderExt;
let app = Router::new()
.route("/", get(echo_headers))
.layer(
ServiceBuilder::new()
.override_request_header(
HeaderName::from_static("x-tenant"),
HeaderValue::from_static("acme"),
)
.insert_request_header_if_not_present(
HeaderName::from_static("x-mode"),
HeaderValue::from_static("default-mode"),
),
);
A request with x-tenant: evil reaches the handler as tenant=acme mode=default-mode multi=[], the same result as the layered form. The multi list is empty for the same reason as in the combining example: no layer in this stack sets x-multi. Use the one-liners when the stack is already a builder and the short form reads better. Use the explicit layers when the code is clearer with the layer names visible, or when the layer needs to be stored, passed around, or applied on its own.
When to use something else instead
This layer is the right tool when the value is a fixed constant or a synchronous derivation from the request itself. It is the wrong tool in two cases. First, when the value needs async work, a database lookup, a call to another service, or reading a file, use a middleware function or a request mapper instead, because those can wait for the work to finish and this layer cannot. Second, when the header logic branches on something the layer cannot see, the matched route, an extractor result, or a value another middleware produced, use a middleware function, which sees the full request including its extensions and can read what earlier middleware inserted. The rule is simple: if the value is a function of the request headers alone, use this layer. If it is a function of anything else, use a middleware function.
Common mistakes
Expecting overriding to append. It replaces. If the handler sees only one value where the client sent one, that is overriding working as designed. Use appending to keep both.
Expecting a default from a layer that only echoes. A layer that copies a client-sent header to the response does nothing when the client sent nothing. A default value is if_not_present job, on the request side, before the handler runs.
Forgetting the set-header feature. Without it, tower_http::set_header does not exist and the import fails. The one-line builder methods additionally need the util feature.
Assuming append order follows listing order in a chain. Chained .layer() calls run last added first, so the last-listed appending layer appends first. In a ServiceBuilder the order follows the listing. Verify with a probe when the order matters.
Doing async work in the closure. MakeHeaderValue is synchronous. A closure that blocks on a lock or a network call stalls the request. Derive the value from the request itself, and move heavier work to a middleware function.
Reading a multi-value header with .get(). .get() returns only the first value. A header built by appending holds several values, and the rest are invisible to .get(). Use .get_all() when the header can hold more than one value.
Summary
The mode is the decision, and everything else follows from it. overriding means the server wins, which is what identity headers need. if_not_present means the client wins, which is what defaults and preferences need. appending means both values travel together, which is what genuinely multi-valued headers need. The value itself is either fixed, computed from the request by a closure, or absent when an Option is None. The same three modes and the same value forms exist on the response side, where the version stamp is the canonical use. When a header value cannot be decided from the request alone, the layer has reached its limit, and a middleware function that can wait and can see the whole request is the tool that takes over.