5 releases

0.2.0 Nov 19, 2023
0.1.3 Nov 18, 2023
0.1.2 Nov 18, 2023
0.1.1 Nov 18, 2023
0.1.0 Nov 18, 2023

#1060 in HTTP server

29 downloads per month

MIT license

85KB
1.5K SLoC

actix-extended-session

Extended session management for Actix Web.

A modified instance of actix-session.

crates.io Documentation Apache 2.0 or MIT licensed Dependency Status

Documentation & Resources


lib.rs:

Extended session management for Actix Web.

actix-extended-session provides an easy-to-use framework to manage sessions in applications built on top of Actix Web. SessionMiddleware is the middleware underpinning the functionality provided by actix-extended-session; it takes care of all the session cookie handling and instructs the storage backend to create/delete/update the session state based on the operations performed against the active Session.

Further reading on sessions:

Getting started

To start using sessions in your Actix Web application you must register SessionMiddleware as a middleware on your App:

use actix_web::{web, App, HttpServer, HttpResponse, Error};
use actix_extended_session::{Session, SessionMiddleware, storage::CookieSessionStore};
use actix_web::cookie::Key;

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    // The secret key would usually be read from a configuration file/environment variables.
    let secret_key = Key::generate();
    HttpServer::new(move ||
            App::new()
            // Add session management to your application using Redis for session state storage
            .wrap(
                SessionMiddleware::new(
                    CookieSessionStore::default(),
                    secret_key.clone()
                )
            )
            .default_service(web::to(|| HttpResponse::Ok())))
        .bind(("127.0.0.1", 8080))?
        .run()
        .await
}

The session state can be accessed and modified by your request handlers using the Session extractor. Note that this doesn't work in the stream of a streaming response.

use actix_web::Error;
use actix_extended_session::Session;
use serde_json::Value;

fn index(session: Session) -> Result<&'static str, Error> {
    // access the session state
    if let Some(count) = session.get::<i32>("counter")? {
        println!("SESSION value: {}", count);
        // modify the session state
        session.insert("counter", Value::from(count + 1));
    } else {
        session.insert("counter", Value::from(1));
    }

    Ok("Welcome!")
}

Dependencies

~16–28MB
~499K SLoC