CORS
CORS is a browser rule that blocks a page on origin A from reading a response from origin B unless B opts in with headers. Servers set those headers; browsers enforce them.
Detailed Explanation
A browser loading https://app.example that fetches https://api.example is a cross-origin request. The browser will not hand the response to JavaScript unless api.example sends Access-Control-Allow-Origin (and, for credentialed requests, a matching origin rather than *, plus Access-Control-Allow-Credentials). Preflight is an OPTIONS request the browser sends first when the real request is not a simple GET/POST. The server must answer the preflight with the allowed methods and headers.
In Axum you add a Tower CORS layer (tower-http::cors) with an explicit origin list, methods, and headers. In Actix you add the CORS middleware. * plus cookies does not work; the spec forbids it. Reflecting any Origin is how people accidentally open the API to every website. Allow the origins you mean.
CORS is not authentication and not CSRF protection. A server that sets Allow-Origin: * on a JSON GET of public data is fine. The same header on a cookie-authenticated POST is a mistake. Same-site cookies, CSRF tokens, and CORS are separate knobs.
Non-browser clients (curl, other servers, mobile apps) ignore CORS. A "CORS error" in the browser console is the browser. The server may have handled the request and the browser hid the body. Debug with the preflight OPTIONS and the response headers, not only the handler log.
When you set CORS: a browser app on a different origin than the API. When you do not: server-to-server calls. When you are tempted by *: only for truly public, unauthenticated reads.
In local development, localhost and 127.0.0.1 are different origins, and http://localhost:5173 is not http://localhost:3000. List both the Vite port and the preview port if you use them. A CORS bug that only happens in prod is often an origin you forgot (www versus apex, or HTTP versus HTTPS).
Code Examples
fn allow_origin(origin: &str) -> bool {
matches!(origin, "https://app.example" | "http://localhost:5173")
}
fn main() {
println!("{}", allow_origin("https://app.example")); // prints: true
println!("{}", allow_origin("https://evil.example")); // prints: false
}Common Gotchas
Reflecting any `Origin` makes every site a client
Allow-list. Do not echo the header you were sent unless you checked it.
Preflight is `OPTIONS`
A missing OPTIONS route looks like a CORS failure even when POST would have worked. The layer must handle OPTIONS.
curl will not show you a CORS bug
Use the browser, or send the `Origin` header yourself and inspect `Access-Control-*`.