CORS Handling Implementation in Rust
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓CORS Handling runs in O(1) time and O(1) space, in Rust as in every other language.
- ✓std contains no HTTP whatsoever, so there is nothing in the standard library to configure.
- ✓Build the policy in a function returning CorsLayer and attach it with .layer() on the Router rather than on one route, since tower layers wrap outward and the CORS layer has to observe the request before the MethodRouter that would reject an undeclared OPTIONS.
- ✓The Rust trap: CorsLayer panics on an impossible policy, and that is deliberate. Setting allow_credentials(true) alongside Any for origins, methods or headers cannot produce a valid response, since every browser rejects Access-Control-Allow-Origin: * together with credentials, so the layer refuses rather than serialising it.
- ✓The borrow checker pushes you into the cheap version by default: the predicate receives &HeaderValue, so checking an origin reads bytes hyper already parsed and allocates nothing at all.
What CORS Handling actually is
CORS Handling in Rust: what you actually reach for
Rust implementation
use axum::http::{header, request::Parts, HeaderValue, Method};
use axum::{routing::get, Json, Router};
use serde::Serialize;
use std::time::Duration;
use tower_http::cors::{AllowOrigin, CorsLayer};
const ALLOWED: [&str; 2] = ["https://app.example.dev", "https://ops.example.dev"];
#[derive(Serialize)]
struct Seats {
seats: u32,
}
async fn seats() -> Json<Seats> {
Json(Seats { seats: 12 })
}
fn cors() -> CorsLayer {
CorsLayer::new()
// The predicate borrows the parsed header bytes; comparing an origin allocates nothing.
.allow_origin(AllowOrigin::predicate(|origin: &HeaderValue, _parts: &Parts| {
origin.to_str().map(|o| ALLOWED.contains(&o)).unwrap_or(false)
}))
.allow_methods([Method::GET, Method::POST, Method::PATCH])
.allow_headers([header::CONTENT_TYPE, header::AUTHORIZATION])
.expose_headers([header::HeaderName::from_static("x-request-id")])
// Credentials combined with Any is a panic, not a header: an impossible policy
// is refused rather than serialised into a response no browser will accept.
.allow_credentials(true)
.max_age(Duration::from_secs(600))
}
#[tokio::main]
async fn main() {
// Layers wrap outward, so CorsLayer sees the request before the MethodRouter that
// would answer an undeclared OPTIONS with 405 and no CORS headers at all.
let app = Router::new().route("/seats", get(seats)).layer(cors());
let listener = tokio::net::TcpListener::bind("127.0.0.1:8080").await.unwrap();
axum::serve(listener, app).await.unwrap();
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Rust-specific trap
Performance in Rust, beyond the O(1)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Rust type or library should I use for CORS Handling?
std contains no HTTP whatsoever, so there is nothing in the standard library to configure. The ecosystem answer is tower_http::cors::CorsLayer, a tower::Layer that composes with axum, warp or any hyper service. It is assembled from http crate types: Method::PATCH, header::AUTHORIZATION, HeaderValue, and AllowOrigin, whose predicate constructor takes a closure of Fn(&HeaderValue, &request::Parts) -> bool. allow_credentials, expose_headers and max_age(Duration) map one to one onto the wire headers, and the layer answers preflights itself without calling the inner service.
What is the most common Rust mistake when implementing CORS Handling?
CorsLayer panics on an impossible policy, and that is deliberate. Setting allow_credentials(true) alongside Any for origins, methods or headers cannot produce a valid response, since every browser rejects Access-Control-Allow-Origin: * together with credentials, so the layer refuses rather than serialising it. Being a panic and not a type error, cargo check stays green and the failure arrives only when that configuration is exercised. The other Rust-shaped trap is ordering: Router::layer() wraps only the routes already registered when it is called, so a .layer(cors) attached before later .route() calls leaves those later-registered routes outside the layer entirely, the fix is to call .layer(cors) last, after every route is registered.
How does CORS Handling actually perform in Rust?
The borrow checker pushes you into the cheap version by default: the predicate receives &HeaderValue, so checking an origin reads bytes hyper already parsed and allocates nothing at all. Preflight replies are assembled from HeaderValue::from_static constants that live in the binary's read-only data, so the OPTIONS path is a handful of slice comparisons with no heap traffic. Cloning a HeaderValue is a refcount bump on Bytes, not a copy, which is why building the Allow-Headers value once and cloning it beats formatting it per request. Time complexity is O(1) and space is O(1).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialBefore paying for Devin, check its student and free-tier options on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.