5 unstable releases
Uses new Rust 2024
| 0.3.1 | Aug 31, 2025 |
|---|---|
| 0.3.0 | Jul 3, 2025 |
| 0.2.0 | Jul 1, 2025 |
| 0.1.1 | Jun 30, 2025 |
| 0.1.0 | Jun 30, 2025 |
#352 in Authentication
43KB
824 lines
rocket_ext
A Rust extension crate for Rocket that provides a flexible and configurable Cross-Origin Resource Sharing (CORS) fairing.
Features
- Easily configure allowed origins, methods, and headers for CORS.
- Support for credentials and max-age.
- Builder pattern for ergonomic configuration.
- Dynamic origin and header handling.
- Fully async and compatible with Rocket's fairing system.
- Options method support for preflight requests.
Usage
Add to your Cargo.toml:
rocket-ext = { version = "*" }
Docs
Docs are available at docs.rs/rocket_ext.
Quick Start
use rocket_ext::cors::Cors;
// Also available under `rocket_ext::prelude::*`
#[rocket::main]
async fn main() -> anyhow::Result<()> {
let cors = Cors::builder()
.with_origin("https://example.com")?
.with_header("X-Custom-Header")
.with_method(rocket::http::Method::Get)
.with_max_age(std::time::Duration::from_secs(3600))
.allow_credentials()
.build()?;
let rocket = rocket::build().attach(cors);
Ok(())
}
API
Building CORS Fairing
Cors::builder(): Start building a CORS configuration..with_origin(origin): Allow a specific origin..with_origins([origins]): Allow multiple origins..with_any_origin(): Allow any origin with the use of a wildcard (*)..with_method(method): Allow a specific HTTP method..with_methods(&[methods]): Allow multiple HTTP methods..with_header(header): Allow a specific header..with_headers(&[headers]): Allow multiple headers..with_any_header(): Allow any header..with_max_age(duration): Set the max age for preflight requests..allow_credentials(): Allow credentials.
Error Handling
- If you attempt to allow credentials without specifying an origin,
a
CorsError::WithCredentialsMissingOriginwill be returned. - If you pass in an invalid origin, a
CorsError::InvalidOriginwill be returned. AnOriginmust contain a scheme, host, and optionally a port. (e.g.http://example.com:8080,https://example.com, orhttp://localhost:8005)
License
MIT OR Apache-2.0
Dependencies
~17–50MB
~807K SLoC