Crate axum_sessions

source ·
Expand description

axum-sessions is a middleware providing cookie-based sessions for axum applications.

SessionLayer provides client sessions via async_session. Sessions are backed by cryptographically signed cookies. These cookies are generated when they’re not found or are otherwise invalid. When a valid, known cookie is received in a request, the session is hydrated from this cookie. The middleware provides sessions via SessionHandle. Handlers use the ReadableSession and WritableSession extractors to read from and write to sessions respectively.


Using the middleware with axum is straightforward:

use axum::{routing::get, Router};
use axum_sessions::{
    async_session::MemoryStore, extractors::WritableSession, PersistencePolicy, SessionLayer,

async fn main() {
    let store = async_session::MemoryStore::new();
    let secret = b"..."; // MUST be at least 64 bytes!
    let session_layer = SessionLayer::new(store, secret);

    async fn handler(mut session: WritableSession) {
            .insert("foo", 42)
            .expect("Could not store the answer.");

    let app = Router::new().route("/", get(handler)).layer(session_layer);


This middleware may also be used as a generic Tower middleware by making use of the SessionHandle extension:

use std::convert::Infallible;

use axum::http::header::SET_COOKIE;
use axum_sessions::{SessionHandle, SessionLayer};
use http::{Request, Response};
use hyper::Body;
use rand::Rng;
use tower::{Service, ServiceBuilder, ServiceExt};

async fn handle(request: Request<Body>) -> Result<Response<Body>, Infallible> {
    let session_handle = request.extensions().get::<SessionHandle>().unwrap();
    let session =;
    // Use the session as you'd like.


let store = async_session::MemoryStore::new();
let secret = rand::thread_rng().gen::<[u8; 128]>();
let session_layer = SessionLayer::new(store, &secret);

let mut service = ServiceBuilder::new()

let request = Request::builder().body(Body::empty()).unwrap();

let response = service.ready().await?.call(request).await?;






Type Definitions

  • A type alias which provides a handle to the underlying session.