CORS allowed headers
Learn which request headers a browser may send cross-origin, how CorsLayer allow headers works, and why a missing header fails the preflight
The origin list decides which places may call an API, and the methods list decides what those places may do. The headers list decides what the request may carry with it. A frontend that logs in sends an Authorization header with a token. A frontend that sends JSON sets a Content-Type header saying the body is JSON. A frontend that talks to a versioned API sends a custom header of its own. The browser asks the server about each of those headers before it sends them cross-origin, and the server answers with the headers it allows. In Axum, that answer is built by allow_headers on CorsLayer from the tower-http crate.
Where This Fits
The origin is the guest list, and the method is what the guest may do. The headers are what the guest may bring through the door. A guest who is on the list, doing an allowed thing, but carrying something the list does not name, is still stopped, and the stopping happens before the real request is ever sent. This page is about writing that third list.
The Smallest Working Version
Start with a small API that reads a token from the Authorization header and returns a profile, and a layer that allows exactly the two headers the frontend sends. Create a project with this Cargo.toml. The cors feature is what makes CorsLayer exist at all, so it must be switched on.
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "=0.8.9"
tokio = { version = "=1.54.1", features = ["full"] }
tower-http = { version = "=0.7.1", features = ["cors"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
Here is the server, split into two files so the tests later on this page can call the same application the server runs. The library file builds the router, and the main file only starts it. The handler checks the token in the simplest possible way, by comparing it with one expected value. That comparison is a teaching stand-in, not a pattern to copy. A real application checks credentials against a session store, a database, or an identity service, and it never stores a secret in source code. A missing or wrong token answers 401 with the shared body {"error": "unauthorized"}, because 401 means the server does not know who is asking.
use axum::{
Json, Router,
http::{HeaderMap, StatusCode, header},
response::{IntoResponse, Response},
routing::get,
};
use serde_json::json;
use tower_http::cors::{Any, CorsLayer};
pub fn app() -> Router {
let cors = CorsLayer::new()
.allow_origin(Any)
.allow_methods([axum::http::Method::GET, axum::http::Method::POST])
.allow_headers([header::AUTHORIZATION, header::CONTENT_TYPE]);
Router::new().route("/profile", get(profile)).layer(cors)
}
async fn profile(headers: HeaderMap) -> Response {
let token = headers
.get(header::AUTHORIZATION)
.and_then(|value| value.to_str().ok())
.and_then(|value| value.strip_prefix("Bearer "));
match token {
Some("secret-token") => Json(json!({ "name": "Ada" })).into_response(),
_ => (
StatusCode::UNAUTHORIZED,
Json(json!({ "error": "unauthorized" })),
)
.into_response(),
}
}
use axum_project::app;
#[tokio::main]
async fn main() {
let app = app();
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Listening on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
Run it with cargo run, then send a preflight for a request that will carry an Authorization header. A preflight is the OPTIONS request the browser sends before a complex cross-origin request, asking whether the real request would be allowed. Curl is not a browser, so it never blocks a response for CORS reasons. That makes curl a good debugging tool, because it shows the raw headers the server sent.
curl -i -X OPTIONS \
-H "Origin: https://frontend.example.com" \
-H "Access-Control-Request-Method: GET" \
-H "Access-Control-Request-Headers: authorization" \
http://127.0.0.1:3000/profile
HTTP/1.1 200 OK
access-control-allow-methods: GET,POST
access-control-allow-headers: authorization,content-type
access-control-allow-origin: *
allow: GET,HEAD
content-length: 0
The browser reads access-control-allow-headers: authorization,content-type, sees that authorization is on the list, and sends the real request with the token. The real request then works.
curl -H "Origin: https://frontend.example.com" \
-H "Authorization: Bearer secret-token" \
http://127.0.0.1:3000/profile
{"name":"Ada"}
Now send a preflight for a header that is not on the list.
curl -i -X OPTIONS \
-H "Origin: https://frontend.example.com" \
-H "Access-Control-Request-Method: GET" \
-H "Access-Control-Request-Headers: x-api-key" \
http://127.0.0.1:3000/profile
HTTP/1.1 200 OK
access-control-allow-methods: GET,POST
access-control-allow-headers: authorization,content-type
access-control-allow-origin: *
allow: GET,HEAD
content-length: 0
The two preflight answers look almost identical, and the status is 200 in both cases. The difference is what the browser does with them. In the second answer, the requested header x-api-key is missing from the allowed list, so the browser never sends the real request and the console shows a CORS error naming the header. The failure shows up in the headers, not in the status, and the handler never runs for the refused request.
Working Setup:
If a preflight for the headers the frontend sends returns access-control-allow-headers with those headers in the list, the setting works. If a preflight for another header returns the same list without it, that is also correct. The browser is the part that compares the two and decides.
What a Header Is
A header is a name and a value attached to an HTTP request or response. The name says what the extra information is, and the value carries it. Authorization: Bearer secret-token is a header whose name is Authorization and whose value is a token with a scheme in front of it. Content-Type: application/json is a header whose name is Content-Type and whose value says the body is JSON. Headers travel with the request, separate from the body, so the server can read them before it looks at the body at all.
Header names are not case sensitive. Authorization, authorization, and AUTHORIZATION are the same header name, and the server treats them the same way. The answers on this page show header names in lowercase, because that is how they travel on the wire. When you write a header name in Rust code, use the constants from the header module, such as header::AUTHORIZATION and header::CONTENT_TYPE, so you never have to worry about spelling or casing.
A beginner can think of headers as labels stuck on the outside of a parcel. The parcel is the body, and the labels say what is inside, who sent it, and what the receiver should do with it. The CORS headers list is the list of labels the receiver is willing to accept from another town.
Simple Headers and the Headers That Trigger a Preflight
Not every header needs permission in advance. A small set of headers, called CORS-safelisted headers, may be sent cross-origin without a preflight. The set is Accept, Accept-Language, Content-Language, and Content-Type, and only when the content type is one of the simple values, such as text/plain. A plain GET that sends only those headers is a simple request, and the browser sends it directly.
Everything else triggers a preflight. Authorization always triggers one, because it carries credentials and it is not on the safelisted set. A Content-Type of application/json triggers one, because JSON is not a simple content type. Any custom header, such as X-Api-Key or X-Total-Count, triggers one. The rule a beginner can carry is short. If the request carries anything beyond the plain basics, the browser asks first.
That rule explains the most common CORS error in an application with a login. The frontend starts sending a token, the request that used to be simple becomes preflighted, and the preflight fails because Authorization was never added to the headers list. The login did not break the API. It changed the shape of the request, and the CORS configuration did not change with it.
Reading the allow_headers Call
The configuration in the smallest example has three pieces, and the last one is the subject of this page.
let cors = CorsLayer::new()
.allow_origin(Any)
.allow_methods([axum::http::Method::GET, axum::http::Method::POST])
.allow_headers([header::AUTHORIZATION, header::CONTENT_TYPE]);
CorsLayer::new() creates a layer that allows nothing at all. No origins, no methods, no headers. That surprises beginners, because a header the handler reads feels like it should work by default. It does not, for CORS purposes. The browser needs the server to say the header is allowed, and the default says nothing is allowed. You must list every header your frontend sends.
allow_headers sets the request headers the browser may send cross-origin, and it decides the value of the Access-Control-Allow-Headers response header. It takes a list of HeaderName values, and the header module provides constants such as AUTHORIZATION and CONTENT_TYPE so you do not have to spell the names as strings. The list is written as an array, and the order inside the array does not matter. The server sends the headers back in the order they were listed, and the browser only checks whether each requested header is present.
The origin in the example is Any, which means any origin, written as a star in the response. The methods list names GET and POST, the two methods the frontend uses. All three lists are present because a working configuration needs all three, and this page keeps the other two simple so the headers list is the part the reader watches.
The List Is Sent Whole, Every Time:
The preflight answer always carries the full headers list, not just the headers that were asked for. Asking about authorization returns authorization,content-type, and asking about x-api-key returns the same authorization,content-type. The browser does the comparing. The server only publishes the list.
How the Browser Decides
The decision the browser makes has three steps, and each one is worth naming, because the error a beginner sees comes from the step that failed.
First, the browser sends the preflight with the headers the real request will carry, listed in Access-Control-Request-Headers. Second, the server answers 200 with the allowed headers list. Third, the browser checks whether every requested header is on that list. If they all are, the real request goes out. If even one is missing, the whole request is refused, and the real request is never sent.
That all-or-nothing rule was checked by running the smallest example and sending a preflight that asked for two headers, one allowed and one not.
curl -i -X OPTIONS \
-H "Origin: https://frontend.example.com" \
-H "Access-Control-Request-Method: GET" \
-H "Access-Control-Request-Headers: authorization, x-api-key" \
http://127.0.0.1:3000/profile
HTTP/1.1 200 OK
access-control-allow-methods: GET,POST
access-control-allow-headers: authorization,content-type
access-control-allow-origin: *
allow: GET,HEAD
content-length: 0
The answer still lists authorization, and the browser still refuses the request, because x-api-key is missing. The console error names the refused header.
Access to fetch at 'http://127.0.0.1:3000/profile' from origin 'https://frontend.example.com' has been blocked by CORS policy: Request header field x-api-key is not allowed by Access-Control-Allow-Headers in preflight response.
The error names the header that was refused, which tells you exactly what to add. The fix is one value in the allow_headers list, not a change to the handler. Two details of that flow catch beginners. The first is that the preflight answer is 200 even when it refuses a header. A 200 status with a missing header is still a refusal, and looking for a 4xx status when debugging a preflight wastes time. The second is that a refused preflight means the handler never runs, so the server logs show no request at all.
Allowing a Custom Header
A custom header is any header the application invents for itself. A frontend might send X-Api-Key with a public key, or X-Request-Id to trace a request through the system. The header module has no constant for a name the application invented, so the name is parsed from a string into a HeaderName.
use axum::http::header::HeaderName;
use tower_http::cors::{Any, CorsLayer};
let cors = CorsLayer::new()
.allow_origin(Any)
.allow_methods([axum::http::Method::GET, axum::http::Method::POST])
.allow_headers([
axum::http::header::AUTHORIZATION,
axum::http::header::CONTENT_TYPE,
"x-api-key".parse::<HeaderName>().unwrap(),
]);
The parse can fail if the string is not a valid header name, so the example unwraps the result. In a learning project, unwrap is fine, because a bad header name is a mistake you want to see at once. The unwrap runs when the server starts, so a bad value crashes the server at startup with a clear message instead of failing quietly on the first request.
A custom header needs the same treatment as a standard one. It must be on the list before the frontend sends it, or the preflight fails. Adding a custom header to the frontend and forgetting the list is the same mistake as forgetting Authorization, and the console error names the header either way.
Allowing Any Header
When the API is public and the headers do not need restricting, every header can be allowed with Any.
use tower_http::cors::{Any, CorsLayer};
let cors = CorsLayer::new()
.allow_origin(Any)
.allow_methods([axum::http::Method::GET, axum::http::Method::POST])
.allow_headers(Any);
A preflight to this configuration answers with access-control-allow-headers: *, where the star means any header is allowed. That is close to CorsLayer::permissive(), but not identical. permissive() also allows any origin, any method, and exposes all response headers. The manual version gives control over each piece separately, which is the point of building the configuration by hand.
Any is the right choice for a public API that anyone may call with any header. It is the wrong choice for an API with a login, where the headers list should name only what the frontend sends. One limit applies to the star and it is worth stating here, even though the full story belongs with credentials. A star headers list never goes together with credentials such as cookies. The layer refuses to build that combination, and the server panics at startup if you try.
Calling allow_headers Twice Does Not Add Headers
Each builder call on CorsLayer overwrites the previous value for that setting, and allow_headers is no exception. Calling it twice keeps only the last list. The wrong code looks like this.
// Wrong - the second call replaces the first, it does not add to it
let cors = CorsLayer::new()
.allow_origin(Any)
.allow_headers([axum::http::header::CONTENT_TYPE])
.allow_headers([axum::http::header::AUTHORIZATION]);
After those two calls, only AUTHORIZATION survives, and a frontend that sends JSON fails its preflight because CONTENT_TYPE is gone. The fix is one call with the whole list.
// Right - every header the frontend sends, in one call
let cors = CorsLayer::new()
.allow_origin(Any)
.allow_headers([axum::http::header::AUTHORIZATION, axum::http::header::CONTENT_TYPE]);
The same overwrite rule applies to the origin and methods lists. If a frontend suddenly stops working after a second header is added, check whether the code chained two calls instead of passing one list.
Chained allow_headers Calls Overwrite Each Other:
Every builder method on CorsLayer replaces the previous value for that setting. Chaining allow_headers twice keeps only the last list. Pass all headers in one call.
Request Headers Are Not Response Headers
The headers list on this page controls request headers, the headers the browser may send to the server. It does not control response headers, the headers JavaScript may read from the response. Those are two different lists, and confusing them is a common mistake.
By default, JavaScript running in a browser may only read a small set of safe response headers, such as Content-Type and Cache-Control. Other headers exist in the response, but the browser hides them from JavaScript unless the server exposes them. That matters when an API returns information in a header, for example a total count for pagination in an X-Total-Count header. Without exposing it, the frontend can see the response body but cannot read the count. The setting that controls that is a different one, and it is not the subject of this page. The point here is only to keep the two directions straight. allow_headers is about what goes in. Reading response headers is about what comes out.
A Plain Text Diagram of the Flow
The headers check runs inside the preflight, before the real request exists.
page wants a cross-origin GET with Authorization
|
v
browser sends OPTIONS preflight
with Access-Control-Request-Headers: authorization
|
v
CorsLayer answers 200
with access-control-allow-headers: authorization,content-type
|
+-- every requested header is on the list
| --> browser sends the real GET with the token
| |
| v
| handler reads the token, response returns
|
+-- a requested header is missing from the list
--> browser stops here
|
v
console CORS error naming the header,
handler never runs
The diagram has one branch that never reaches the server. That branch is the whole point of the preflight. The browser asks first, and a refusal costs one extra request instead of a real request that would have been thrown away.
Testing It
Two tests cover the two outcomes of this page. Each test sends a preflight through the router with oneshot and checks the allowed headers header. The tower crate provides oneshot, which sends one mock request directly through the router without any network connection. A preflight is built by hand, with the method set to OPTIONS and the three preflight headers set, because no route in the application handles OPTIONS directly. The layer intercepts it.
use axum::{
body::Body,
http::{Request, StatusCode},
};
use axum_project::app;
use tower::ServiceExt;
async fn preflight(requested_headers: &str) -> axum::response::Response {
app()
.oneshot(
Request::builder()
.method("OPTIONS")
.uri("/profile")
.header("origin", "https://frontend.example.com")
.header("access-control-request-method", "GET")
.header("access-control-request-headers", requested_headers)
.body(Body::empty())
.unwrap(),
)
.await
.unwrap()
}
#[tokio::test]
async fn preflight_for_allowed_header_lists_it() {
let response = preflight("authorization").await;
assert_eq!(response.status(), StatusCode::OK);
let allowed = response
.headers()
.get("access-control-allow-headers")
.unwrap()
.to_str()
.unwrap();
assert!(allowed.contains("authorization"));
assert!(allowed.contains("content-type"));
}
#[tokio::test]
async fn preflight_for_disallowed_header_does_not_list_it() {
let response = preflight("x-api-key").await;
assert_eq!(response.status(), StatusCode::OK);
let allowed = response
.headers()
.get("access-control-allow-headers")
.unwrap()
.to_str()
.unwrap();
assert!(!allowed.contains("x-api-key"));
}
The second test is the one that guards the behaviour beginners find hardest to believe. It asserts that the refused preflight still returns status 200. If somebody changed the layer to reject preflights with an error status, that test would fail, and the failure would be a signal that the code no longer matches how the browser actually behaves. The header is the whole answer, so the test reads the header, not just the status.
The tower crate is needed as a dev dependency.
[dev-dependencies]
tower = { version = "=0.5.3", features = ["util"] }
Run the tests with cargo test.
Common Beginner Mistakes
Forgetting Authorization When a Login Is Added
// Wrong - the frontend now sends a token, but the list was never updated
let cors = CorsLayer::new()
.allow_origin(Any)
.allow_methods([axum::http::Method::GET, axum::http::Method::POST])
.allow_headers([axum::http::header::CONTENT_TYPE]);
This is the most common headers mistake in an application with a login. The API worked before the login existed, because the requests were simple. The first request with a token becomes preflighted, and the preflight fails. The fix is to add header::AUTHORIZATION to the list in the same edit that adds the token to the frontend.
Forgetting Content-Type for a JSON Request
A frontend that sends JSON sets Content-Type: application/json, which is not a simple content type, so the request gets a preflight. If CONTENT_TYPE is missing from the list, the preflight fails even though the token header is allowed. Both headers must be on the list, because the browser checks every requested header, not just the first one.
Passing a String Where a Header Name Belongs
// Wrong - allow_headers takes HeaderName values, not plain strings
let cors = CorsLayer::new().allow_headers(["authorization", "content-type"]);
This does not compile, because a plain string is not a HeaderName. The fix is the constants from the header module for standard headers, and a parsed HeaderName for custom ones. The compiler error points at the type mismatch, and it is worth reading, because it names the type the method actually wants.
One Missing Header Refuses the Whole Request:
The browser checks every requested header against the list. One missing header refuses the entire request, even when every other header is allowed. When a preflight fails, read the console error, find the one header it names, and add that one header.
Forgetting the cors Feature
Without features = ["cors"] on the tower-http dependency, the CorsLayer type does not exist and the import fails with a compile error saying the module could not be found. The fix is one word in Cargo.toml. If the compiler cannot find tower_http::cors, check the feature list before anything else.
Final Complete Example
Here is everything from this page put together. A profile route that reads a token, a data route that accepts JSON, a custom header on the list, and the tests from the section above. The project layout is the one the smallest example used, with the application split into a library so the tests can call it. The token check is the same teaching stand-in as before, and a real application replaces the comparison with a lookup against a session store, a database, or an identity service.
use axum::{
Json, Router,
http::{HeaderMap, StatusCode, header},
response::{IntoResponse, Response},
routing::{get, post},
};
use serde::Serialize;
use serde_json::json;
use tower_http::cors::{AllowOrigin, CorsLayer};
#[derive(Serialize)]
struct Message {
text: String,
}
pub fn app() -> Router {
let cors = CorsLayer::new()
.allow_origin(AllowOrigin::list([
"https://frontend.example.com".parse::<axum::http::HeaderValue>().unwrap(),
"https://admin.example.com".parse::<axum::http::HeaderValue>().unwrap(),
]))
.allow_methods([axum::http::Method::GET, axum::http::Method::POST])
.allow_headers([
header::AUTHORIZATION,
header::CONTENT_TYPE,
"x-api-key".parse().unwrap(),
]);
Router::new()
.route("/profile", get(profile))
.route("/api/data", post(create_data))
.layer(cors)
}
async fn profile(headers: HeaderMap) -> Response {
let token = headers
.get(header::AUTHORIZATION)
.and_then(|value| value.to_str().ok())
.and_then(|value| value.strip_prefix("Bearer "));
match token {
Some("secret-token") => Json(json!({ "name": "Ada" })).into_response(),
_ => (
StatusCode::UNAUTHORIZED,
Json(json!({ "error": "unauthorized" })),
)
.into_response(),
}
}
async fn create_data(Json(message): Json<Message>) -> Json<Message> {
Json(message)
}
use axum_project::app;
#[tokio::main]
async fn main() {
let app = app();
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Listening on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "=0.8.9"
tokio = { version = "=1.54.1", features = ["full"] }
tower-http = { version = "=0.7.1", features = ["cors"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
[dev-dependencies]
tower = { version = "=0.5.3", features = ["util"] }
The create_data handler takes a JSON body, which is why CONTENT_TYPE is on the list. A POST with a JSON body always gets a preflight, and the preflight asks about both the content type and the token header. The custom X-Api-Key header is on the list because the admin frontend sends it with its requests. Each header on the list earns its place, because a real request sends it.
Run the checks with these commands.
cargo check
cargo test
cargo run
Summary
The headers list is the third guest list, and it is checked before the real request exists, header by header, with no partial credit. The browser lists every header the real request will carry, the server publishes the whole allowed list in its answer, and the browser refuses the request if even one header is missing. A missing header still returns status 200, and the handler never runs, which is why a missing header shows up as silence in the server logs and an error naming the header in the browser console. The most common version of this mistake arrives with a login, because the first token turns a simple request into a preflighted one, and the configuration has to change in the same edit as the frontend.
The decision framework to carry forward is simple. List exactly the headers the frontend sends, and nothing else. When the console names a refused header, add that one header, and check the other two lists at the same time, because a request that passes the headers check still needs its origin and its method on their lists. The next question after what the request may carry is whether the browser may also send the credentials that prove who is asking, and that question is answered by the credentials setting.