Note: This site is currently "Under construction". I'm migrating to a new version of my site building software. Lots of things are in a state of disrepair as a result (for example, footnote links aren't working). It's all part of the process of building in public. Most things should still be readable though.

Set, Read, And Delete Cookies In axum

Code

[package]
name = "axum_cookies"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "0.6" 
tokio = { version = "1", features = ["full"] }
tower-cookies = "0.9"

Code

use axum::response::IntoResponse;
use axum::routing::get;
use axum::{response::Html, Router};
use std::net::SocketAddr;
use tower_cookies::{Cookie, CookieManagerLayer, Cookies};

#[tokio::main]
async fn main() {
    let routes_all = Router::new()
        .route("/", get(set_cookie_handler))
        .route("/read-cookie", get(read_cookie_handler))
        .route("/delete-cookie", get(delete_cookie_handler))
        .layer(CookieManagerLayer::new());
    let addr = SocketAddr::from(([127, 0, 0, 1], 8484));
    axum::Server::bind(&addr)
        .serve(routes_all.into_make_service())
        .await
        .unwrap();
}

async fn set_cookie_handler(cookies: Cookies) -> impl IntoResponse {
    cookies.add(Cookie::new("delta", "echo"));
    Html("Cookie has been sent to browser".to_string())
}

async fn read_cookie_handler(cookies: Cookies) -> impl IntoResponse {
    match cookies.get("delta") {
        Some(cookie) => {
            dbg!(&cookie.value());
            Html(format!("Cookie value is: {}", cookie.value()))
        }
        None => Html(format!("No cookie found")),
    }
}

async fn delete_cookie_handler(cookies: Cookies) -> impl IntoResponse {
    cookies.remove(Cookie::new("delta", ""));
    Html("Cookie deleted".to_string())
}

// add CookieMangerLayer. Must be under
// other routes that want to use cookies

References