rust
32 lines · 7 steps
Configuring CORS on an Axum Router
How to build an Axum router that applies a tuned CORS policy across its JSON API routes.
Explained by
highlit
1use std::time::Duration;
2
3use axum::{
4 http::{header, HeaderValue, Method},
5 routing::{get, post},
6 Json, Router,
7};
8use serde_json::{json, Value};
9use tower_http::cors::CorsLayer;
10
11pub fn app() -> Router {
12 let cors = CorsLayer::new()
13 .allow_origin("https://app.example.com".parse::<HeaderValue>().unwrap())
14 .allow_methods([Method::GET, Method::POST, Method::PUT, Method::DELETE])
15 .allow_headers([header::AUTHORIZATION, header::CONTENT_TYPE])
16 .expose_headers([header::CONTENT_DISPOSITION])
17 .allow_credentials(true)
18 .max_age(Duration::from_secs(3600));
19
20 Router::new()
21 .route("/api/profile", get(profile))
22 .route("/api/sessions", post(create_session))
23 .layer(cors)
24}
25
26async fn profile() -> Json<Value> {
27 Json(json!({ "id": 42, "name": "Ada Lovelace" }))
28}
29
30async fn create_session() -> Json<Value> {
31 Json(json!({ "token": "eyJhbGciOi...", "expires_in": 3600 }))
32}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A CORS layer must explicitly whitelist origins, methods, and headers rather than defaulting to permissive.
- 2Tower middleware applied with `.layer` wraps every route on the router uniformly.
- 3`allow_credentials(true)` requires a concrete origin — wildcards are rejected by browsers when credentials are sent.
Related explainers
rust
use axum::{ body::Bytes, extract::State, http::StatusCode,
Handling raw byte uploads in Axum
extractors
shared-state
request-limits
Intermediate
7 steps
go
package main import ( "net/http"
How route groups nest in Gin
routing
middleware
api versioning
Intermediate
6 steps
rust
use axum::{ extract::{Query, State}, http::StatusCode, Json,
Paginated, filtered product listing in Axum
pagination
query-parameters
sql-filtering
Intermediate
8 steps
rust
use axum::{ extract::FromRef, http::StatusCode, response::{IntoResponse, Redirect},
Signed cookie sessions in Axum
sessions
cookies
authentication
Intermediate
8 steps
rust
use axum::{ http::StatusCode, response::{IntoResponse, Response}, Json,
How a custom error type maps to HTTP in Axum
error-handling
enums
trait-implementation
Intermediate
7 steps
rust
use std::collections::HashMap; use std::sync::{Arc, Mutex}; use std::thread;
Aggregating metrics across threads in Rust
concurrency
shared-state
mutex
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/configuring-cors-on-an-axum-router-explained-rust-fa26/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.