laravel-rust 0.1.4

Laravel for Rust: a full-stack Rust web framework.
Documentation
# Session

- [Introduction]#introduction
    - [Configuration]#configuration
    - [The database session table]#the-database-session-table
    - [Redis sessions]#redis-sessions
- [Interacting with the session]#interacting-with-the-session
    - [Retrieving data]#retrieving-data
    - [Storing data]#storing-data
    - [Flash data]#flash-data
    - [Deleting data]#deleting-data
    - [Regenerating the session ID]#regenerating-the-session-id
- [Session stores of your own]#session-stores-of-your-own
- [Testing]#testing

<a name="introduction"></a>
## 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.

Laravel'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](middleware.md#middleware-groups) 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 name="configuration"></a>
### Configuration

The `SESSION_DRIVER` environment variable configures where Laravel 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.

Laravel includes several built-in session drivers:

- `database` stores sessions in a [table]#the-database-session-table in your database.
- `redis` stores sessions in [Redis / Valkey]#redis-sessions.
- `file` stores sessions on disk in `storage/framework/sessions`.
- `cookie` stores the session in an encrypted cookie, requiring no server-side storage. It's the default when `SESSION_DRIVER` isn't set.
- `memory` stores sessions in memory and clears them when the server restarts, making it ideal for tests.

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.

<a name="the-database-session-table"></a>
### 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](migrations.md) that holds only the `session::table!` macro, which creates the table:

```rust
// database/migrations/2026_01_01_000000_create_sessions_table.rs
laravel::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.rs
use laravel::db::AnyTransaction;

pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::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](database.md#configuration) 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 Laravel automatically deletes expired rows on 2 out of every 100 requests using a [lottery](lottery.md). To customize these cleanup odds, set the `lottery` field in `src/config/session.rs`:

```rust
// src/config/session.rs
use laravel::config::session::Session;
use laravel::config::{self, Env};
use laravel::lottery::Lottery;

#[config::section]
fn session(env: &Env) -> Session {
    Session {
        lottery: Lottery::odds(1, 50),
        ..Session::from_env(env)
    }
}
```

<a name="redis-sessions"></a>
### Redis sessions

To store sessions in Redis, add Laravel's `redis` Cargo feature to `laravel-rust` in your `Cargo.toml`:

```toml
[dependencies]
laravel-rust = { 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](redis.md#configuration), 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.

<a name="interacting-with-the-session"></a>
## Interacting with the session

To read or write session data in a handler, take a `Session` argument. `Session` is included in the [prelude](prelude.md):

```rust
use laravel::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 `laravel::Result<&Session>`.

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

<a name="retrieving-data"></a>
### 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();
```

<a name="storing-data"></a>
### 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. Laravel 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");
```

<a name="flash-data"></a>
### 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 Laravel deletes it:

```rust
use laravel::prelude::*;

pub async fn store(session: Session) -> laravel::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`](responses.md#redirecting-with-flashed-session-data):

```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!");
```

<a name="deleting-data"></a>
### 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](csrf.md), so forms the user already has open can still be submitted:

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

session.flush();
```

<a name="regenerating-the-session-id"></a>
### 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. Laravel's [authentication](authentication.md) 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 Laravel's built-in authentication, [`auth.logout()`](authentication.md#logging-out) 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.

<a name="session-stores-of-your-own"></a>
## Session stores of your own

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

```rust
use std::time::Duration;

use laravel::session::{Identity, SessionStore, Write};

pub struct MemcachedStore {
    // Your Memcached client...
}

impl SessionStore for MemcachedStore {
    async fn read(&self, id: &str, lifetime: Duration) -> laravel::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,
    ) -> laravel::Result<()> {
        // Store the payload under the ID, and expire it after the lifetime...
        todo!()
    }

    async fn destroy(&self, id: &str) -> laravel::Result<()> {
        // Delete the payload stored under the ID...
        todo!()
    }
}
```

Laravel 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 laravel::prelude::*;

Application::configure()
    .with_services(|app| {
        app.sessions().extend("memcached", |_app| async { Ok(MemcachedStore {}) });
    })
```

The factory receives the [container](container.md), 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](packages.md#service-providers) `register` method.

<a name="testing"></a>
## 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 laravel::testing::prelude::*;

#[laravel::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](testing.md#cookies-and-sessions).