When I pushed this application to production it did not have any CORS protection anywhere. It is a really small application so it would not matter much if it did not have this protection. Unfortunately, we live in an internet where bad requests from bad neighborhoods can be sent to any application. To prevent that CORS is a must even if modern browsers come with this feature inbuilt.
It was a quick setup. First, you need to have Tower in your Cargo.toml. I'll be using Axum 0.8 for this. Now, since it would be "tedious" hardcoding the origin in the code we'll grab it in our .env file. Thus, we will use the Dotenvy crate. Add the Dotenvy crate to your Cargo.toml using: cargo add dotenvy.
Somewhere in your .env file add this line:
APP_URL=http://localhost:3000
In your routes.rs or the file where you have defined your routes you can proceed to do something like this:
use axum::{
routing::{get},
Router,
middleware::from_fn_with_state,
http::{Method, HeaderValue},
};
use tower_http::cors::{CorsLayer, Any};
use dotenvy::dotenv;
use std::env;
use crate::controllers::hello;//This crate is in a 'controllers' folder somewhere
/// Create and configure the application router
pub fn create_router(state: AppState) -> Router {
dotenv().ok(); // Reads our .env file
// Configure CORS layer
//Fetch APP URL from the .env file
let appurl = env::var("APP_URL").unwrap_or_else(|_| "http://localhost:3000".to_string());
let cors = CorsLayer::new()
// Set APP URL as the origin
// If you want to allow any origin use .allow_origin(Any) but this would be insecure
.allow_origin(appurl.parse::().unwrap())
// Allow the standard methods
.allow_methods([Method::GET, Method::POST, Method::PUT, Method::DELETE])
// Allow the standard headers and any custom headers
.allow_headers(Any);
Router::new()
// Public routes
.route("/say-hello", get(hello::hello_handler))
.route("/some-other-route", get(hello::other_route_handler))
.layer(cors)//Set CORS protection guards
.with_state(state)
.fallback(axum::routing::get(|| async { "404 - Page not found" }))
}
Then in your main.rs file you can initiate your routes with create_router().
Much has been stripped out here but this should give you a general idea of how to set up CORS for your Rust applications.
WORDCOUNT: 328 words.