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 serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
rust
use std::cmp::{Ordering, Reverse}; use std::collections::BinaryHeap; use std::fs::File; use std::io::{self, BufRead, BufReader, BufWriter, Lines, Write};
K-way merge of sorted logs in Rust
binary-heap
k-way-merge
streaming-io
Intermediate
8 steps
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
rust
use axum::{ extract::{Path, State}, response::sse::{Event, KeepAlive, Sse}, };
Streaming import progress with SSE in Axum
server-sent-events
streams
watch-channel
Advanced
7 steps
rust
use std::f64::consts::PI; #[derive(Debug, Clone, Copy)] pub struct LatLng {
Building geographic bounding boxes in Rust
geospatial
value-types
option
Intermediate
7 steps
rust
use chrono::{Duration, NaiveDate}; #[derive(Debug)] pub struct DateRange {
Parsing and iterating date ranges in Rust
error-handling
iterators
parsing
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.