Expand description
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!")
}
Modules§
- config
- Configuration options to tune the behaviour of
SessionMiddleware
. - storage
- Pluggable storage backends for session state.
Structs§
- Session
- The primary interface to access and modify session state.
- Session
GetError - Error returned by
Session::get
. - Session
Middleware - A middleware for session management in Actix Web applications.
Enums§
- Session
Status - Status of a
Session
.
Traits§
- Session
Ext - Extract a
Session
object from variousactix-web
types (e.g.HttpRequest
,ServiceRequest
,ServiceResponse
).