CorsLayer

Learn how to configure Cross-Origin Resource Sharing (CORS) in Axum using tower-http CorsLayer, with step-by-step examples and common pitfalls.

A web page and an API often live on different origins. The page might be served from https://app.example.com while the API runs on https://api.example.com. A browser treats those as different places, and by default it refuses to let JavaScript on one place read responses from the other. That refusal has a name, the same-origin policy, and it exists to protect users. Cross-Origin Resource Sharing, usually shortened to CORS, is the mechanism a server uses to relax that policy in a controlled way. In Axum, CORS is handled by CorsLayer from the tower-http crate. This page takes you from knowing nothing about CORS to configuring CorsLayer for the situations you will actually meet, allowing any origin during development, restricting to known origins in production, handling cookies and credentials, and testing the result with curl.

What an Origin Is

An origin is a combination of three parts, the scheme, the host, and the port. The scheme is http or https. The host is the domain name, such as frontend.example.com. The port is the number after the colon, such as 3000. Two addresses are the same origin only when all three parts match.

That rule is stricter than it looks. The addresses https://frontend.com and http://frontend.com are different origins, because the scheme differs. The addresses https://frontend.com and https://backend.com are different origins, because the host differs. The addresses https://frontend.com:3000 and https://frontend.com:4000 are different origins, because the port differs. During local development, http://localhost:3000 and http://localhost:5173 are different origins too, which is why a local frontend and a local API hit CORS errors even though both run on the same machine.

The same-origin policy says that JavaScript running on a page from one origin may only read responses from that same origin. Without that rule, a malicious website could use your browser to call your bank website and read your account data, because your browser would attach your cookies to the request automatically. The policy blocks that by default. CORS lets a server say, in a precise way, which other origins may read its responses, which HTTP methods they may use, and which headers they may send. The browser enforces the server decision. The server never sees a CORS error itself. The browser blocks the JavaScript from reading the response, and the error appears in the browser console.

Simple Requests and Preflight Requests

The browser handles cross-origin requests in two ways, depending on how complex the request is. A simple request uses only a GET, HEAD, or POST method, only a few basic headers, and a simple content type such as text/plain. The browser sends a simple request directly and then checks the response for CORS headers before letting JavaScript read it.

Anything more complex is a preflighted request. A PUT or DELETE method, a custom header such as Authorization, or a JSON content type makes the request complex. Before sending the real request, the browser sends an OPTIONS request, called a preflight, that asks the server whether the real request would be allowed. The preflight carries three headers. Origin says where the page making the request lives. Access-Control-Request-Method says which method the real request will use. Access-Control-Request-Headers lists the headers the real request will carry. The server answers with the CORS headers, and only then does the browser send the real request.

CorsLayer handles both kinds of request automatically. You configure the rules once, and the middleware adds the right headers to responses and answers preflight requests before they ever reach your handlers. You do not write an OPTIONS handler yourself.

A Basic Axum App Without CORS

Start with a plain Axum server with two endpoints, so you can see the problem before you fix it. Create a project and add the dependencies. The cors feature enables CorsLayer, and serde is declared because the examples on this page return JSON.

Cargo.toml
[package]
name = "cors-demo"
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"] }

Here is the starting application, in src/main.rs.

src/main.rs
use axum::{routing::get, Json, Router};
use serde::Serialize;

#[derive(Serialize)]
struct Message {
    text: String,
}

async fn hello() -> &'static str {
    "Hello from the API!"
}

async fn api_data() -> Json<Message> {
    Json(Message {
        text: "Some data".to_string(),
    })
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(hello))
        .route("/api/data", get(api_data));

    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();
}

If you open http://127.0.0.1:3000/ directly in a browser, you see the message, because typing an address in the address bar is not a cross-origin JavaScript request. If a JavaScript page served from http://localhost:5500 fetches http://127.0.0.1:3000/api/data, the browser blocks the response and the console shows an error like this.

Access to fetch at 'http://127.0.0.1:3000/api/data' from origin 'http://localhost:5500' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

The server answered the request normally. The browser received the response and refused to hand it to the JavaScript because the response carried no Access-Control-Allow-Origin header. That missing header is the whole problem, and CorsLayer is the fix.

Curl does not enforce CORS:

Curl is not a browser, so it never blocks a response for CORS reasons. That makes curl a good debugging tool. It shows you the raw headers the server sent, without the browser getting in the way. If curl shows the Access-Control-Allow-Origin header and the browser still blocks the request, the header value does not match the page origin, or another rule such as credentials is wrong.

The First Fix, Allowing Everything

The simplest CORS configuration allows any origin, any method, and any header. That is useful during development and for public APIs that anyone may call. The constructor is CorsLayer::permissive(), and it is applied with one .layer() call on the router.

src/main.rs
use axum::{routing::get, Json, Router};
use serde::Serialize;
use tower_http::cors::CorsLayer;

#[derive(Serialize)]
struct Message {
    text: String,
}

async fn hello() -> &'static str {
    "Hello from the API!"
}

async fn api_data() -> Json<Message> {
    Json(Message {
        text: "Some data".to_string(),
    })
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(hello))
        .route("/api/data", get(api_data))
        .layer(CorsLayer::permissive());

    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();
}

The only new line is .layer(CorsLayer::permissive()). The permissive constructor sets four things. All origins are allowed, all methods are allowed, all request headers are allowed, and all response headers are exposed. Credentials are not allowed, which is covered later on this page. With this layer in place, the browser accepts cross-origin responses from any origin, and the fetch from http://localhost:5500 starts working.

You can watch the layer answer a preflight with curl. This command sends an OPTIONS request that pretends to come from a page on another origin, asking to use PUT with an authorization header.

curl -i -X OPTIONS \
  -H "Origin: https://any.example.com" \
  -H "Access-Control-Request-Method: PUT" \
  -H "Access-Control-Request-Headers: authorization" \
  http://127.0.0.1:3000/api/data

Run against the permissive server, this returns status 200 and these headers, verified by running the exact program above.

access-control-allow-origin: *
access-control-allow-methods: *
access-control-allow-headers: *

The star means any value is allowed. The browser reads that answer, decides the real PUT request is permitted, and sends it. A plain GET request to the same server returns access-control-allow-origin: * and access-control-expose-headers: * as well, because permissive() also exposes all response headers. The expose header does not appear on the preflight response, only on real responses, which is normal.

Permissive CORS is not for production:

CorsLayer::permissive() allows every website on the internet to make requests to your API and read the responses. That is fine for a public API with no sensitive data and no login. It is not fine for an API that handles private data or requires authentication. Restrict the origins, methods, and headers before you ship, as the sections below show.

The Default, Nothing Is Allowed

CorsLayer::new() is the opposite starting point. It creates a layer that allows no origins, no methods, and no headers at all. Not even the simple methods GET, HEAD, and POST are allowed. If you use it without any configuration, no cross-origin request succeeds. That is the safe default, and it is the right base for a production configuration, because every permission you add is a deliberate choice.

Configuration is done by chaining builder methods on the layer. A builder method is a method that returns a new version of the layer with one setting changed, so you can chain several calls in a row. The methods you will use most are allow_origin, which sets the origins that may call the API, allow_methods, which sets the HTTP methods they may use, allow_headers, which sets the request headers they may send, allow_credentials, which sets whether cookies and authorization may be sent, expose_headers, which sets which response headers JavaScript may read, and max_age, which sets how long the browser may cache a preflight answer.

Allowing Specific Origins

In most real applications, you know exactly which frontend origins should be allowed. Instead of permissive(), you list them. An origin is passed as a HeaderValue, which is the http crate type for a single header value. A plain string must be parsed into a HeaderValue first, and the parse can fail if the string is not a valid header value, so the examples unwrap the result.

src/main.rs
use axum::{http::HeaderValue, routing::get, Router};
use tower_http::cors::CorsLayer;

async fn hello() -> &'static str {
    "Hello from the API!"
}

#[tokio::main]
async fn main() {
    let cors = CorsLayer::new()
        .allow_origin("https://frontend.example.com".parse::<HeaderValue>().unwrap())
        .allow_methods([axum::http::Method::GET]);

    let app = Router::new()
        .route("/", get(hello))
        .layer(cors);

    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

With this configuration, a request from https://frontend.example.com receives an Access-Control-Allow-Origin header with that exact origin, and the browser lets the page read the response. A request from any other origin receives the same header with the same value, https://frontend.example.com, because a single exact origin is sent on every response, whatever origin asked. The browser is the part that enforces the rule. It compares the header value with the origin of the page making the request, and it blocks the response when the two differ. The protection comes from that comparison, not from the server withholding the header. The server still runs the handler and still sends the response body in both cases.

That fixed-value behaviour is specific to a single exact origin. The list form behaves differently. With a list, only origins on the list get the header echoed back, and an unlisted origin gets no header at all.

Calling allow_origin Twice Does Not Add Origins

This is the mistake that catches almost everyone. Calling allow_origin twice does not accumulate origins. Each call overwrites the previous one, so only the last origin survives. That was verified at runtime. A layer built with two chained allow_origin calls, first https://first.example.com and then https://second.example.com, answered a request from the first origin with access-control-allow-origin: https://second.example.com, and answered a request from the second origin the same way. The first origin was gone entirely.

To allow several origins, pass them all in a single call. AllowOrigin::list takes a collection of HeaderValue values and allows each of them.

src/main.rs
use axum::http::HeaderValue;
use tower_http::cors::{AllowOrigin, CorsLayer};

let cors = CorsLayer::new()
    .allow_origin(AllowOrigin::list([
        "https://frontend.example.com".parse::<HeaderValue>().unwrap(),
        "https://admin.example.com".parse::<HeaderValue>().unwrap(),
    ]))
    .allow_methods([axum::http::Method::GET]);

Tested at runtime, a request from https://frontend.example.com received that origin back, a request from https://admin.example.com received its own origin back, and a request from an unlisted origin received no Access-Control-Allow-Origin header at all. The server echoes the requesting origin when it is on the list, and stays silent when it is not. You can also pass an array of HeaderValue values directly to allow_origin, because an array converts into an AllowOrigin the same way a list does.

Chained allow_origin calls overwrite each other:

Every builder method on CorsLayer replaces the previous value for that setting. Chaining allow_origin twice keeps only the last origin, and the same is true of allow_methods and allow_headers. If your frontend suddenly stops working after you add a second origin, check whether you chained two calls instead of passing one list.

Allowing Any Origin Without permissive

If you are building a public API, you can allow any origin without allowing everything else. The Any value, imported from tower_http::cors, means any origin.

src/main.rs
use tower_http::cors::{Any, CorsLayer};

let cors = CorsLayer::new().allow_origin(Any);

This answers every request with Access-Control-Allow-Origin: *, but it does not touch methods or headers, which stay at their default of nothing allowed. It is a narrower tool than permissive(), and it is the right one when the API is public but you still want to control which methods and headers clients may use.

Origins Decided by a Rule

Sometimes the list of allowed origins is not fixed. A product that gives each customer their own subdomain, such as customer1.example.com and customer2.example.com, cannot list them all in advance. AllowOrigin::predicate lets you decide with a function that receives the request origin and returns true or false.

src/main.rs
use axum::http::HeaderValue;
use tower_http::cors::{AllowOrigin, CorsLayer};

let cors = CorsLayer::new().allow_origin(AllowOrigin::predicate(
    |origin: &HeaderValue, _parts: &axum::http::request::Parts| {
        origin.as_bytes().ends_with(b".example.com")
    },
));

The closure receives the origin as bytes and checks whether it ends with .example.com. Any subdomain passes, and any other domain fails. The second parameter carries the request parts, which you can use when the decision needs more than the origin itself, for example checking a header. There is also an async version, AllowOrigin::async_predicate, for decisions that need to wait on something, such as fetching the allowed list from a database. And AllowOrigin::mirror_request() allows any origin by echoing the request origin back, which is useful when credentials are involved, as the credentials section explains.

Allowing Methods and Headers

A CorsLayer created with new() allows no methods and no headers at all. That surprises beginners, because GET feels like it should work by default. It does not, for CORS purposes. The browser needs the server to say the method is allowed, and the default says nothing is allowed. You must list every method and header your frontend uses.

src/main.rs
use axum::http::{header, Method};
use tower_http::cors::{Any, CorsLayer};

let cors = CorsLayer::new()
    .allow_origin(Any)
    .allow_methods([Method::GET, Method::POST])
    .allow_headers([header::AUTHORIZATION, header::CONTENT_TYPE]);

The allow_methods call takes a list of Method values, imported from axum::http. The allow_headers call 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. If your frontend sends a PUT request or a custom header such as X-Requested-With and you have not allowed it, the preflight fails and the browser never sends the real request. The error in the console names the method or header that was refused, which tells you exactly what to add.

You can allow any method or any header with Any, in the same way as origins.

src/main.rs
use tower_http::cors::{Any, CorsLayer};

let cors = CorsLayer::new()
    .allow_origin(Any)
    .allow_methods(Any)
    .allow_headers(Any);

That is close to permissive(), but not identical. Permissive() also sets expose_headers to Any, and it sets nothing else. The manual version gives you control over each piece separately, which is the point of building the configuration by hand.

Letting JavaScript Read Response Headers

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 your 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 expose_headers method controls this. It takes a list of header names, or Any to expose everything.

src/main.rs
use axum::http::header;
use tower_http::cors::CorsLayer;

let cors = CorsLayer::new()
    .allow_origin("https://frontend.example.com".parse::<axum::http::HeaderValue>().unwrap())
    .allow_methods([axum::http::Method::GET])
    .expose_headers([header::CONTENT_LENGTH, "x-total-count".parse().unwrap()]);

With this configuration, a cross-origin response carries Access-Control-Expose-Headers: content-length, x-total-count, and JavaScript may read both headers. The string "x-total-count" is parsed into a header name, which works for any custom header name. Remember that permissive() already exposes all headers, so this setting only matters when you build the configuration by hand.

Handling Credentials, Cookies and Authorization

Some frontends need to send cookies, for session management, or an Authorization header with a token. For those to work across origins, two things must happen. The server must set Access-Control-Allow-Credentials: true, and the server must not use a wildcard star for the allowed origin. It must echo the specific origin from the request. The browser enforces both rules, and the CORS specification forbids the combination of credentials with a star.

CorsLayer handles this with the allow_credentials method, combined with a specific origin or a list of origins.

src/main.rs
use axum::http::{header, HeaderValue, Method};
use tower_http::cors::CorsLayer;

let cors = CorsLayer::new()
    .allow_origin("https://frontend.example.com".parse::<HeaderValue>().unwrap())
    .allow_methods([Method::GET, Method::POST])
    .allow_headers([header::AUTHORIZATION, header::CONTENT_TYPE])
    .allow_credentials(true);

With this configuration, a request from https://frontend.example.com receives two headers, Access-Control-Allow-Origin: https://frontend.example.com, with the exact origin rather than a star, and Access-Control-Allow-Credentials: true. The browser then allows the JavaScript to send credentials and read the response. The frontend must also ask for credentials, for example by setting credentials to include in a fetch call, or the browser will not send them even though the server allows it. Both sides have to agree.

Credentials with a wildcard origin panics when the layer is applied:

If you combine .allow_credentials(true) with .allow_origin(Any), the program panics when the layer is applied to the router, with the message "Invalid CORS configuration: Cannot combine Access-Control-Allow-Credentials: true with Access-Control-Allow-Origin: *". The same panic happens if credentials are combined with allow_methods(Any), allow_headers(Any), or expose_headers(Any). The panic does not happen when you build the layer. It happens when the layer is attached, which is usually at startup, so you will see it immediately when you run the server. Always use a specific origin or a list of origins when credentials are enabled.

There is one more way to handle credentials, for cases where the origin cannot be listed in advance. CorsLayer::very_permissive() allows credentials and mirrors the request origin, method, and headers back in the response. It answers each preflight with the exact values the browser asked for, and it echoes the request origin instead of a star, so the credentials rule is satisfied. It exposes no headers by default. That is a convenient setting for an internal tool, and a dangerous one for a public API, because it allows any origin that asks.

Caching Preflight Answers with max_age

Every preflight is an extra round trip. If a page makes many requests with the same method and headers, the browser repeats the preflight each time unless the server tells it how long the answer may be cached. The max_age method sets that duration.

src/main.rs
use std::time::Duration;
use axum::http::{header, Method};
use tower_http::cors::{Any, CorsLayer};

let cors = CorsLayer::new()
    .allow_origin(Any)
    .allow_methods([Method::GET, Method::POST])
    .allow_headers([header::CONTENT_TYPE])
    .max_age(Duration::from_secs(3600));

The server then includes Access-Control-Max-Age: 3600 in the preflight response, and the browser may reuse that answer for one hour instead of asking again. A long cache makes repeated requests faster, and a short cache makes policy changes take effect sooner. One hour is a common middle ground. Note that max_age only affects preflight caching. It does not cache the real responses.

Private Network Access

Browsers have an extra rule for pages on the public internet that try to reach a server on a private network, such as a device on a home network at 192.168.1.10. The browser sends a preflight with an Access-Control-Request-Private-Network header, and the server must answer with Access-Control-Allow-Private-Network: true. CorsLayer supports this with allow_private_network(true). Most applications never need it, because their API and their users are both on the public internet. If you build a web page that talks to a local device, this is the setting that unblocks it.

src/main.rs
use tower_http::cors::{Any, CorsLayer};

let cors = CorsLayer::new()
    .allow_origin(Any)
    .allow_private_network(true);

Applying CorsLayer at Different Scopes

So far the layer has been applied to the whole router with .layer(), which covers every route in that router. Axum also lets you apply middleware to one route only, which is useful when different parts of the API need different CORS policies. A public read-only endpoint might allow any origin, while an admin endpoint allows only one.

One Route Only

The .layer() method on a MethodRouter, which is the value returned by get(handler), wraps only that route.

src/main.rs
use axum::{routing::get, Router};
use tower_http::cors::CorsLayer;

async fn hello() -> &'static str {
    "Hello from the API!"
}

async fn api_data() -> &'static str {
    "Some data"
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(hello))
        .route("/api/data", get(api_data).layer(CorsLayer::permissive()));

    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Only /api/data carries CORS headers now. A cross-origin request to / returns a response with no CORS headers, and the browser blocks it. That is precise control, and it is the right tool when only one route needs to be callable from a browser page.

Beware of route_layer, which sounds like the same thing and is not. Router::route_layer applies the layer to all routes that have been added to the router so far, not to one route. If you call it after adding two routes, both get the layer. To limit the scope to one route, use .layer() on that route as shown above, or put the routes that need the layer in their own router.

Combining CorsLayer with Other Layers

When an application has several layers, ServiceBuilder from the tower crate composes them into one stack with a predictable order. The first layer listed runs first on the way in, which means it is the outermost layer.

src/main.rs
use axum::{routing::get, Router};
use tower::ServiceBuilder;
use tower_http::{cors::CorsLayer, trace::TraceLayer};

async fn hello() -> &'static str {
    "Hello from the API!"
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(hello))
        .layer(
            ServiceBuilder::new()
                .layer(TraceLayer::new_for_http())
                .layer(CorsLayer::permissive()),
        );

    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

This example needs tower as a dependency for ServiceBuilder, tower-http with the trace and cors features, and tracing-subscriber if you want to see the trace output. In this stack, TraceLayer sees the request first, then CorsLayer, then the handler. The response goes back through CorsLayer, which adds the headers, and then TraceLayer.

CORS belongs near the outside of the stack:

CORS should sit outside layers that may reject a request early, such as authentication. If authentication rejects a request before CorsLayer runs, the error response carries no CORS headers, and the browser reports a CORS error instead of the real 401 status. That misleads everyone debugging it. Put CorsLayer early in a ServiceBuilder stack, or as one of the last .layer() calls on the router, so it always runs.

A Complete Production Configuration

Here is a full example that reflects a typical production setup. One allowed origin, credentials enabled, specific methods and headers, a preflight cache of one hour, and an exposed header for pagination. The Cargo.toml is the one from the start of this page, with the cors feature and serde declared.

src/main.rs
use axum::{
    http::{header, HeaderValue, Method},
    routing::get,
    Json, Router,
};
use serde::Serialize;
use std::time::Duration;
use tower_http::cors::CorsLayer;

#[derive(Serialize)]
struct ApiResponse {
    message: String,
}

async fn hello() -> &'static str {
    "Hello, world!"
}

async fn get_data() -> Json<ApiResponse> {
    Json(ApiResponse {
        message: "Data from API".to_string(),
    })
}

#[tokio::main]
async fn main() {
    let cors = CorsLayer::new()
        .allow_origin("https://frontend.example.com".parse::<HeaderValue>().unwrap())
        .allow_methods([Method::GET, Method::POST, Method::PUT, Method::DELETE])
        .allow_headers([header::AUTHORIZATION, header::CONTENT_TYPE])
        .allow_credentials(true)
        .expose_headers([header::CONTENT_LENGTH])
        .max_age(Duration::from_secs(3600));

    let app = Router::new()
        .route("/", get(hello))
        .route("/api/data", get(get_data))
        .layer(cors);

    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running on http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

Each setting in this example earns its place. The origin is one exact value, because credentials are enabled and the specification forbids a star there. Four methods are listed, because the frontend uses all four. Two headers are listed, because the frontend sends an authorization token and JSON bodies. Credentials are enabled, because the frontend keeps its session in a cookie. The content length header is exposed, because the frontend reads it. The preflight cache is one hour, because the policy rarely changes. Nothing is allowed that the frontend does not use.

You do not need an OPTIONS route for preflight requests. CorsLayer intercepts them before they reach your router and answers them itself. Adding your own OPTIONS handler is unnecessary, and it can conflict with the layer if the handler and the layer disagree about the answer.

Your CORS setup is working:

Run the server and send a request from the allowed origin with curl, using -H "Origin: https://frontend.example.com". If the response includes access-control-allow-origin: https://frontend.example.com and access-control-allow-credentials: true, the configuration is correct. Send the same request from another origin and you will see the same header value, the allowed origin, not the origin you sent. That is expected for a single exact origin, which is sent on every response. The browser compares the value with the page origin and blocks the response when they differ, and that comparison is the test that matters.

Testing CORS Without a Browser

You can test every CORS rule with curl, because curl shows the raw response headers and never enforces the policy itself. To simulate a simple cross-origin request, send an Origin header with a GET.

curl -i -H "Origin: https://frontend.example.com" http://127.0.0.1:3000/api/data

Look for access-control-allow-origin in the response. Its value should be the origin you sent, or a star, depending on the configuration. If the header is missing, the origin is not allowed, or the layer is not applied to that route.

To simulate a preflight, send an OPTIONS request with the three preflight headers.

curl -i -X OPTIONS \
  -H "Origin: https://frontend.example.com" \
  -H "Access-Control-Request-Method: PUT" \
  -H "Access-Control-Request-Headers: Authorization, Content-Type" \
  http://127.0.0.1:3000/api/data

A working configuration answers with status 200 and the allowed methods and headers. If the response has no CORS headers, the preflight failed, which usually means the method or one of the headers is not in the allowed lists. The browser console names the refused method or header when a real page hits the same problem, and that message points at the exact list to fix.

A Reusable Configuration Function

When an application has more than one router, or when main is getting crowded, a small function that returns a configured CorsLayer keeps the setup in one place.

src/main.rs
use axum::http::{header, HeaderValue, Method};
use tower_http::cors::CorsLayer;

fn cors_layer() -> CorsLayer {
    CorsLayer::new()
        .allow_origin("https://frontend.example.com".parse::<HeaderValue>().unwrap())
        .allow_methods([Method::GET, Method::POST])
        .allow_headers([header::CONTENT_TYPE])
        .allow_credentials(true)
}

The function is then used with .layer(cors_layer()) wherever the layer is needed. The return type is CorsLayer, and the function takes no arguments, so it is easy to call from anywhere in the application. If the allowed origin changes between development and production, this function is the one place to change it, ideally by reading the value from configuration rather than hard coding it.

Common Mistakes and How to Avoid Them

Using permissive() in production is the most dangerous mistake. It allows any website to call the API and read the responses. Always restrict origins in production, and treat permissive() as a development tool.

Forgetting to enable the cors feature in tower-http is the most common compile error. Without features = ["cors"] in Cargo.toml, the CorsLayer type does not exist and the import fails. The fix is one word in Cargo.toml.

Mixing credentials with a wildcard is the most confusing runtime error. The program panics when the layer is applied, with a message that names the exact invalid combination. Always use a specific origin or a list when credentials are enabled, and never combine credentials with allow_methods(Any), allow_headers(Any), or expose_headers(Any) either.

Not allowing a method or header the frontend uses is the most common browser error. If the frontend sends a PUT request or a custom header and the preflight does not allow it, the browser never sends the real request. The console message names the refused value, so add it to the matching list.

Applying CorsLayer inside another layer that returns early is a subtle ordering mistake. If authentication rejects a request before CorsLayer runs, the error response has no CORS headers and the browser reports a CORS error. Put CorsLayer outside authentication so every response, including errors, carries the headers.

Adding OPTIONS routes by hand is unnecessary work. CorsLayer answers preflights itself. A hand written OPTIONS handler can disagree with the layer and produce confusing results. Leave preflight handling to the layer unless you have a specific reason to take it over.

Summary

CORS is a browser rule, not a server rule, and that single fact explains almost every confusing error. The server always answers. The browser decides whether JavaScript may read the answer, based on the headers the server sent. CorsLayer is the part of the server that sends those headers, and its configuration is a list of permissions, origins, methods, headers, credentials, exposed headers, and a preflight cache.

The decision framework to carry forward has two branches. If the API is public, with no login and no private data, allow any origin and be explicit about methods and headers. If the API has a login, a session, or private data, list the exact origins, enable credentials only with those exact origins, and allow only the methods and headers the frontend actually uses. Start restrictive and open up one permission at a time when the browser console tells you it is needed. Each permission you add is a deliberate choice, and the configuration reads as a record of those choices.