dust

Session

Introduction

Since HTTP is stateless, sessions provide a way to store information about a user across multiple requests. For example, sessions keep track of who is logged in, store the color theme a user selected, or carry a status message across a redirect.

dust-framework's StartSession middleware loads the session at the beginning of each request and saves it when the response is sent. Because the web middleware group includes StartSession, every route in src/routes/web.rs automatically has access to the session. Routes in src/routes/api.rs are stateless and don't start a session.

A session belongs to one request. A queued job, a console command, and a scheduled task have no session, so pass the user's ID or the values the job needs as arguments instead of reading them from the session.

Configuration

The SESSION_DRIVER environment variable configures where dust-framework stores session data. New applications use the database driver, which is the right choice for most applications because every server shares the same sessions and sessions survive deploys.

dust-framework includes several built-in session drivers:

Driver Stores sessions in Best for
database A table in your database Most applications, especially with several servers
redis Redis / Valkey High-traffic applications that already run Redis
file storage/framework/sessions on disk A single server with a persistent disk
cookie An encrypted cookie, with no server-side storage Tiny sessions or a stateless application; the fallback when SESSION_DRIVER is unset
memory Process memory, cleared on restart Tests and local development

A database or redis driver lets every server share sessions and survives a deploy. The file and memory drivers are tied to one process or machine, so avoid them when you run more than one server.

Sessions expire after SESSION_LIFETIME minutes of inactivity (120 minutes by default). The cookie driver always encrypts session data. To encrypt session data stored by the other drivers as well, set SESSION_ENCRYPT=true:

ini
SESSION_DRIVER=database
SESSION_LIFETIME=120
SESSION_ENCRYPT=false

You may customize the session cookie itself using these environment variables, though the defaults work well for most applications:

Variable Sets Default
SESSION_COOKIE The cookie's name the app's name, as my_app_session
SESSION_DOMAIN The cookie's Domain none
SESSION_SECURE_COOKIE Whether the cookie is sent only over HTTPS when APP_URL is https
SESSION_SAME_SITE The cookie's SameSite lax
SESSION_EXPIRE_ON_CLOSE Whether the session ends when the browser closes false

The cookie driver works well as long as your sessions stay small. Browsers ignore cookies larger than 4 KB, and that limit includes any old input and validation errors flashed after a failed form submission, so a single long text field can overflow the cookie. In debug mode and in tests, a session that exceeds the cookie size limit fails the request. If you run into this limit, store less in the session or switch to the database or redis driver.

The database session table

The database driver stores sessions in a sessions table. New applications include this table in their initial migration alongside the users table. If your application doesn't have it yet, add a migration that holds only the session::table! macro, which creates the table:

rust
// database/migrations/2026_01_01_000000_create_sessions_table.rsdust::session::table!();

If you'd like to change the table, such as storing UUIDs in user_id because your users use UUIDs as primary keys, replace the macro with the migration it stands for and edit it. For UUIDs, define user_id with table.uuid("user_id"):

rust
// database/migrations/2026_01_01_000000_create_sessions_table.rsuse dust::db::AnyTransaction;pub async fn migrate(tx: &mut AnyTransaction<'_>) -> dust::Result<()> {    tx.schema()        .create("sessions", |table| {            table.string("id").primary();            table.big_integer("user_id").nullable().index();            table.string("ip_address").length(45).nullable();            table.text("user_agent").nullable();            table.long_text("payload");            table.timestamp("last_activity").index();        })        .await}

Each row records the signed-in user's ID, IP address, and user agent from the session's most recent request, which makes it possible to display a list of active devices to your users.

By default, the database driver uses your default database connection and a table named sessions. To use a different connection or table name, set SESSION_CONNECTION or SESSION_TABLE.

You don't need to schedule a cleanup job, because dust-framework automatically deletes expired rows on 2 out of every 100 requests using a lottery. To customize these cleanup odds, set the lottery field in src/config/session.rs:

rust
// src/config/session.rsuse dust::config::session::Session;use dust::config::{self, Env};use dust::lottery::Lottery;#[config::section]fn session(env: &Env) -> Session {    Session {        lottery: Lottery::odds(1, 50),        ..Session::from_env(env)    }}

Redis sessions

To store sessions in Redis, add dust-framework's redis Cargo feature to dust-framework in your Cargo.toml:

toml
[dependencies]dust-framework = { version = "0.1", features = ["database-postgres", "redis"] }

Then select the redis driver in your .env file:

ini
SESSION_DRIVER=redis

The driver uses your default Redis connection, or the connection named by SESSION_CONNECTION. Redis expires idle sessions automatically, and sessions use a separate Redis database from your cache by default so clearing your cache doesn't sign users out.

Interacting with the session

To read or write session data in a handler, take a Session argument. Session is included in the prelude:

rust
use dust::prelude::*;pub async fn show(session: Session) -> String {    let theme: Option<String> = session.get("theme");    format!("You're using the {} theme", theme.as_deref().unwrap_or("light"))}

Route middleware may take a Session argument as well. Taking Session on a route that doesn't run StartSession, such as an api route, fails the request with a server error. If your handler already takes a Request argument, or runs on a route that might not have a session, call request.session() instead, which returns a dust::Result<&Session>.

[!NOTE] dust-framework saves the session after your handler returns and before it sends the response body. If you return a streamed response, make any session changes in the handler before returning the stream.

Retrieving data

The get method retrieves an item from the session and deserializes it into the type you ask for. It returns None if the key is missing or if the stored value doesn't match the requested type. You may use "dot" notation to read nested values:

rust
let theme: Option<String> = session.get("settings.theme");let locale: String = session.get("settings.locale").unwrap_or_else(|| "en".to_owned());

To check whether an item is present and not null, use has. To check whether a key exists even if its value is null, use exists:

rust
if session.has("settings") {    // ...}if session.exists("settings") {    // ...}

To retrieve an item and remove it from the session in one step, use pull. To retrieve every item in the session as a JSON map, use all:

rust
let coupon: Option<String> = session.pull("coupon");let data = session.all();

Storing data

To store an item in the session, call put with a key and any value that implements Serialize:

rust
session.put("theme", "dark");

You may also use "dot" notation to store nested values. dust-framework creates the nested JSON object automatically, so you may later read it back into a struct (or a serde_json::Value) with session.get("settings"):

rust
#[derive(Deserialize)]pub struct Settings {    pub theme: String,    pub locale: String,}session.put("settings.theme", "dark");session.put("settings.locale", "fr");let settings: Option<Settings> = session.get("settings");

Flash data

Sometimes you only want to store an item in the session for the next request, such as a confirmation banner after a form submission. The flash method stores a value for the current request and the next request, after which dust-framework deletes it:

rust
use dust::prelude::*;pub async fn store(session: Session) -> dust::Result<Redirect> {    // Create the post...    session.flash("status", "Post published!");    Ok(Redirect::to("/posts"))}

On the next request, read the flashed value with session.get("status"). You may also flash data directly on a redirect with with:

rust
Ok(Redirect::to("/posts").with("status", "Post published!"))

If you need to keep flash data around for an additional request, call reflash to keep all flashed items, or keep to preserve only specific keys:

rust
session.reflash();session.keep(["status", "error"]);

To flash an item for the current request only, use now:

rust
session.now("status", "Post published!");

Deleting data

To remove a single item from the session, call forget. To clear all data from the session at once, call flush. Calling flush preserves the session's CSRF token, so forms the user already has open can still be submitted:

rust
session.forget("coupon");session.flush();

Regenerating the session ID

Regenerating the session ID prevents attackers from exploiting a session fixation attack by planting a known session ID in a user's browser before they log in. dust-framework's authentication regenerates the session ID automatically when a user logs in, but if you build a custom login flow, call regenerate. Your existing session data is preserved under the new ID:

rust
session.regenerate()?;

When a user logs out, call invalidate to clear all session data and generate a new session ID in one step. If you're using dust-framework's built-in authentication, auth.logout() already calls invalidate for you:

rust
session.invalidate()?;

Both regenerate and invalidate also generate a new CSRF token. With a server-side driver such as database or redis, the old session ID stops working immediately. Because the cookie driver stores no state on the server, a copy of an old session cookie remains valid until it expires, so use a server-side driver when logging out must revoke the session everywhere.

The methods you'll reach for most often:

Method What it does
get(key) Reads a value as Option<T>, using "dot" notation for nested keys.
has(key) / exists(key) Checks for a non-null value, or for a key of any value.
put(key, value) Writes any Serialize value.
pull(key) Reads a value and removes it in one step.
flash(key, value) / now(key, value) Stores a value for the next request, or only this one.
reflash() / keep(keys) Keeps flashed data for another request.
forget(key) / flush() Removes one key, or every key but the CSRF token.
regenerate() / invalidate() Replaces the session ID, preserving or clearing the data.

Session stores of your own

If you need to store sessions in a backend that dust-framework's built-in drivers don't cover, such as Memcached, implement the SessionStore trait:

rust
use std::time::Duration;use dust::session::{Identity, SessionStore, Write};pub struct MemcachedStore {    // Your Memcached client...}impl SessionStore for MemcachedStore {    async fn read(&self, id: &str, lifetime: Duration) -> dust::Result<Option<String>> {        // Return the payload stored under the ID...        todo!()    }    async fn write(        &self,        id: &str,        payload: String,        lifetime: Duration,        identity: &Identity,        write: Write,    ) -> dust::Result<()> {        // Store the payload under the ID, and expire it after the lifetime...        todo!()    }    async fn destroy(&self, id: &str) -> dust::Result<()> {        // Delete the payload stored under the ID...        todo!()    }}

dust-framework serializes and encrypts the session for you, so your store saves each payload and returns it unchanged:

  • read returns the payload stored under the ID, or None when no session exists or when the session has been idle longer than lifetime.
  • write stores the payload. When write is Write::Existing, update the record only if the session still exists so a session destroyed by a logout while the request ran stays destroyed. identity holds the user's ID, IP address, and user agent for stores that record them.
  • destroy deletes a session, such as after its ID is regenerated or invalidated.

Two additional methods are optional. Implement collect_garbage to delete expired sessions when your backend doesn't expire keys automatically, and implement destroy_others to delete a user's other sessions when they change their password if your store can look up sessions by user ID.

Once you've implemented the store, register it as a driver in src/app.rs and select it with SESSION_DRIVER=memcached:

rust
use dust::prelude::*;Application::configure()    .with_services(|app| {        app.sessions().extend("memcached", |_app| async { Ok(MemcachedStore {}) });    })

The factory receives the container, so it may resolve services such as a client registered as a singleton. A package may register a custom driver by calling app.sessions().extend(...) inside its service provider's register method.

Testing

Tests use the memory session driver by default. To seed a request with session data, call with_session. To assert what the request left in the session (including flash data), use assert_session_has and assert_session_missing:

rust
use dust::testing::prelude::*;#[dust::test]async fn placing_an_order_uses_the_coupon(app: Application) {    app.post("/orders")        .with_session(json!({ "coupon": "WELCOME10" }))        .await        .assert_session_has("status", "Order placed!")        .assert_session_missing("coupon");}

To verify only that a key exists in the session without asserting its exact value, use assert_session_present. To learn more about inspecting session values with custom assertions or carrying a session across multiple requests, check out the testing guide's section on cookies and sessions.