Sessions

rustdocs (main)

Sessions are a common convention in web frameworks, allowing for a safe and secure way to associate server-side data with a given http client (browser). Trillium's session storage is built on the async-session crate, which allows us to share session stores with tide. Currently, these session stores exist:

1

The memory store and cookie store should be avoided for use in production applications. The memory store will lose all session state on server process restart, and the cookie store makes different security tradeoffs than the database-backed stores. If possible, use a database.

❗The session handler must be used in conjunction with the cookie handler, and it must run after the cookie handler. This particular interaction is also present in other frameworks, and is due to the fact that regardless of which session store is used, sessions use a secure cookie as a unique identifier.

use trillium::Conn;
use trillium_cookies::CookiesHandler;
use trillium_sessions::{MemoryStore, SessionConnExt, SessionHandler};

pub fn main() {
    env_logger::init();

    trillium_smol::run((
        CookiesHandler::new(),
        SessionHandler::new(MemoryStore::new(), "01234567890123456789012345678901123"),
        |conn: Conn| async move {
            let count: usize = conn.session().get("count").unwrap_or_default();
            conn.with_session("count", count + 1)
                .ok(format!("count: {count}"))
        },
    ));
}