Session extractor in handlers

Learn how to read a session inside a handler with the Session extractor, get the stored user id back, and answer when the session is empty

Login stored the user id in the session. Something has to read it back, and that something is a handler. This page is about that read: putting Session in a handler's arguments, asking it for the stored user id, and deciding what the handler does when the session has nothing stored. A handler that can read the session is a handler that knows who is asking, and that is what turns a login into a personal page.

Where This Fits

The layer carries the session, and the login handler writes the user id into it. Neither of those helps a page that wants to show the visitor their own data. The missing piece is the read, done inside an ordinary handler, with no cookie parsing and no store calls. This page adds that read, on a profile route that returns the logged-in user. The value comes out of the session the same way it went in, under the same key, in the same type.

Think of the ticket again. Login handed the visitor a ticket and kept the coat. This page is the attendant checking the ticket number, finding the coat, and reading the name tag sewn inside it. The handler never sees the ticket itself. It sees the coat.

The Smallest Working Version

The profile handler below reads the user id from the session, loads that user from the database, and returns the user as JSON. When the session has no user id, it answers 401 with the shared error body. The login handler from the login page is included unchanged, because without it there is no session to read, and the public route stays so the difference between an open route and a personal one stays visible.

The Cargo.toml, the migrations, the error type, and the entry point are the same as on the login page. Only the library file grows, by one handler and one route:

src/lib.rs
pub mod errors;

use argon2::{
    Argon2,
    password_hash::{PasswordHash, PasswordVerifier},
};
use axum::{
    Json, Router,
    extract::State,
    routing::{get, post},
};
use errors::{AppError, HandlerResult};
use serde::{Deserialize, Serialize};
use sqlx::PgPool;
use tower_sessions::{Expiry, MemoryStore, Session, SessionManagerLayer};
use time::Duration;

#[derive(Debug, Serialize, sqlx::FromRow)]
pub struct User {
    pub id: i32,
    pub name: String,
    pub email: String,
}

#[derive(Debug, Deserialize)]
pub struct LoginInput {
    pub email: String,
    pub password: String,
}

#[derive(Debug, sqlx::FromRow)]
struct LoginRow {
    id: i32,
    password_hash: Option<String>,
}

pub fn app(pool: PgPool) -> Router {
    let session_store = MemoryStore::default();
    let session_layer = SessionManagerLayer::new(session_store)
        .with_secure(false)
        .with_expiry(Expiry::OnInactivity(Duration::days(7)));

    Router::new()
        .route("/login", post(login))
        .route("/me", get(me))
        .route("/public", get(public))
        .layer(session_layer)
        .with_state(pool)
}

async fn public() -> &'static str {
    "Anyone can read this."
}

fn password_matches(password: &str, stored_hash: &str) -> bool {
    let parsed = match PasswordHash::new(stored_hash) {
        Ok(parsed) => parsed,
        Err(_) => return false,
    };
    Argon2::default()
        .verify_password(password.as_bytes(), &parsed)
        .is_ok()
}

async fn login(
    State(pool): State<PgPool>,
    session: Session,
    Json(input): Json<LoginInput>,
) -> HandlerResult<Json<User>> {
    let row = sqlx::query_as::<_, LoginRow>(
        "SELECT id, password_hash FROM users WHERE email = $1",
    )
    .bind(&input.email)
    .fetch_optional(&pool)
    .await
    .map_err(|_| AppError::InternalError)?;

    let user_id = match row {
        Some(row) => match row.password_hash {
            Some(hash) if password_matches(&input.password, &hash) => row.id,
            _ => return Err(AppError::Unauthorized),
        },
        None => return Err(AppError::Unauthorized),
    };

    session
        .insert("user_id", user_id)
        .await
        .map_err(|_| AppError::InternalError)?;
    session
        .cycle_id()
        .await
        .map_err(|_| AppError::InternalError)?;

    let user = sqlx::query_as::<_, User>(
        "SELECT id, name, email FROM users WHERE id = $1",
    )
    .bind(user_id)
    .fetch_one(&pool)
    .await
    .map_err(|_| AppError::InternalError)?;

    Ok(Json(user))
}

async fn me(
    State(pool): State<PgPool>,
    session: Session,
) -> HandlerResult<Json<User>> {
    let user_id = match session.get::<i32>("user_id").await {
        Ok(Some(id)) => id,
        Ok(None) => return Err(AppError::Unauthorized),
        Err(_) => return Err(AppError::InternalError),
    };

    let user = sqlx::query_as::<_, User>(
        "SELECT id, name, email FROM users WHERE id = $1",
    )
    .bind(user_id)
    .fetch_optional(&pool)
    .await
    .map_err(|_| AppError::InternalError)?
    .ok_or(AppError::Unauthorized)?;

    Ok(Json(user))
}

Start the server with cargo run, log in to get a cookie, and then ask for the profile twice, once with the cookie and once without:

curl -c cookies.txt -X POST http://127.0.0.1:3000/login -H 'Content-Type: application/json' -d '{"email":"ada@example.com","password":"test-password-123"}'
curl -b cookies.txt http://127.0.0.1:3000/me
curl http://127.0.0.1:3000/me

The output is:

{"id":1,"name":"Ada","email":"ada@example.com"}
{"id":1,"name":"Ada","email":"ada@example.com"}
{"error":"unauthorized"}

The first command is the login, which returns the user and saves the cookie. The second sends the cookie, so the handler finds the user id in the session, loads the user, and returns the same JSON. The third sends no cookie, so the session is empty, and the handler answers 401. The same route gives a personal answer to a logged-in visitor and a refusal to a stranger, and the only difference between the two requests is the cookie.

Working Setup:

If the profile returns the user JSON with the cookie and {"error":"unauthorized"} without it, the extractor is working. The session is being read inside the handler, and the empty case is handled instead of crashing.

How the Extractor Gets the Session

The Session argument looks like magic until the path it travels is spelled out. The session layer runs before the handler, reads the cookie from the request, loads the record from the store, and places the finished Session value into the request's extensions. Extensions are a side pocket on the request where middleware can leave values for handlers to pick up. The extractor is the pickup: when Axum builds the handler's arguments, it looks in the extensions for a Session, clones it, and hands it to the handler.

Cloning matters here. The Session value is cheap to clone because the clones share the same underlying record. The handler and the layer both hold a handle to the same session, so a value the handler inserts is visible to the layer when it saves at the end of the request. Two handlers never share a Session across requests, because each request gets its own load from the store.

The extractor can fail, and its failure has a specific shape. If no session layer is attached to the router, there is nothing in the extensions, and the extractor rejects the request with status 500 and the message Can't extract session. Is 'SessionManagerLayer' enabled?. That 500 is not the handler's doing. The handler never runs. The rejection happens before it, at argument building time. The fix is always the layer, never the handler, and the mistake is covered in full below.

Reading the Stored Value

The read itself is one call with three outcomes, and the handler answers each one differently:

let user_id = match session.get::<i32>("user_id").await {
    Ok(Some(id)) => id,
    Ok(None) => return Err(AppError::Unauthorized),
    Err(_) => return Err(AppError::InternalError),
};

session.get::<i32>("user_id") asks the session for the value stored under the key "user_id" and rebuilds it as an i32. The ::<i32> part is a turbofish, Rust syntax for saying which type a generic function should use, and it must match the type that was inserted. Login inserted an i32, so the handler asks for an i32. The call is async, so it needs .await, because the value may need loading from the store.

The return type is Result<Option<i32>>, which packs three cases into one value. Ok(Some(id)) is the good case: a value is stored, and it is the user id. Ok(None) means no value is stored under that key, which is the ordinary state of a session that never logged in. That maps to Unauthorized and status 401, because the server cannot tie the request to any user. Err(_) means the read itself failed, which happens when the stored value cannot be rebuilt as an i32, for example because something stored a string under the same key. That is a bug in the program, not a problem with the visitor, so it maps to InternalError and status 500.

A missing value is not a server error:

Ok(None) and Err(_) look similar in a quick read, but they mean opposite things. None says the visitor never logged in, which is routine, and the answer is 401. Err says the program stored something it cannot read back, which is a bug, and the answer is 500. Collapsing both arms into one error hides real bugs behind a login failure.

The rest of the handler is a database lookup by the id from the session. fetch_optional returns None when the id has no row, which happens when the user was deleted after logging in. That also maps to Unauthorized, because the session points at a user who no longer exists, and there is nobody to return. A database failure maps to InternalError, as everywhere else in this project.

The Concept Behind the Read

The important idea is that the handler never touches the cookie. It never reads a header, never parses an id out of text, and never calls the store. The layer did all of that before the handler ran, and the handler receives the finished session as an ordinary argument. That is what an extractor is for: it moves the mechanics of getting data out of the request into a reusable piece, and leaves the handler with a plain value to use.

The mental model is a function argument like any other, except Axum fills it in. State(pool) is filled from the router's state. Json(input) is filled from the request body. Session is filled from the request's extensions. The handler's job is to use the values, not to fetch them, and the same handler with the same arguments would work the same way in a test that builds the request by hand.

Why Handlers Read Instead of the Layer Deciding

The layer could have decided who may call the route, and the middleware page does exactly that for groups of routes. But the layer cannot decide what a single handler does with the user id. One handler needs the id to load a profile. Another needs it to list that user's notes. A third needs it to count that user's visits. Each handler uses the same value differently, so the read belongs in the handler, where the use is. The layer's job ends at delivery. The handler's job starts at use. Keeping that split is what lets one session serve many handlers without the layer knowing what any of them do.

A Richer Example - Profile and Visit Count

The profile handler only reads. A handler that reads, changes, and writes back shows the other half of the Session API in the same shape. This example adds a route that counts how many times the logged-in visitor has called it, storing the count in the session under the key "visits":

src/lib.rs
async fn me(
    State(pool): State<PgPool>,
    session: Session,
) -> HandlerResult<Json<User>> {
    let user_id = match session.get::<i32>("user_id").await {
        Ok(Some(id)) => id,
        Ok(None) => return Err(AppError::Unauthorized),
        Err(_) => return Err(AppError::InternalError),
    };
    let user = sqlx::query_as::<_, User>(
        "SELECT id, name, email FROM users WHERE id = $1",
    )
    .bind(user_id)
    .fetch_optional(&pool)
    .await
    .map_err(|_| AppError::InternalError)?
    .ok_or(AppError::Unauthorized)?;
    Ok(Json(user))
}

async fn record_visit(
    session: Session,
) -> HandlerResult<Json<serde_json::Value>> {
    let visits: i32 = session
        .get("visits")
        .await
        .map_err(|_| AppError::InternalError)?
        .unwrap_or(0);
    session
        .insert("visits", visits + 1)
        .await
        .map_err(|_| AppError::InternalError)?;
    Ok(Json(serde_json::json!({ "visits": visits + 1 })))
}

Register the route next to the profile route:

Router::new()
    .route("/login", post(login))
    .route("/me", get(me))
    .route("/visit", get(record_visit))
    .route("/public", get(public))
    .layer(session_layer)
    .with_state(pool)

record_visit does not check for a login. It reads "visits" with get, turns a missing value into zero with unwrap_or(0), inserts the count plus one, and returns the new count. The first call with a fresh cookie answers {"visits":1}, the second answers {"visits":2}. The get here has no turbofish, because the let visits: i32 annotation already tells the compiler which type to rebuild, and either spelling works. The point of the example is the shape: read a value, compute a new one, write it back, all through the same Session the profile handler uses. A visitor's count and a visitor's identity live side by side in one session, under different keys, and neither handler knows about the other.

Dropping One Value With remove

Not every write is an insert. remove takes one key out of the session and returns the value it removed, or None when nothing was stored under that key. A handler that forgets a stored display name, for example, would call it like this:

async fn forget_name(session: Session) -> HandlerResult<&'static str> {
    let _removed: Option<String> = session
        .remove("name")
        .await
        .map_err(|_| AppError::InternalError)?;
    Ok("Name forgotten.")
}

The removed value comes back as an Option<String>, because the key may have held nothing. The return type is part of the call: remove::<String> would say the same thing with a turbofish instead of the annotation. Removing one key leaves the rest of the session untouched, so the user id stays stored and the visitor stays logged in. That is the difference between removing a value and ending a session: remove drops one fact, while logout drops everything, and the logout page covers that difference in full.

Remove returns what it removed:

The value remove returns is useful when the handler needs to confirm what was stored, such as logging which display name was forgotten, or moving a value out of the session and into the database. When the handler only needs the key gone, the return value can be ignored with let _removed, as above.

Reading Several Values in One Handler

A handler can read as many keys as it needs, and each read is independent. A dashboard handler might read the user id, a stored display name, and a stored preference, each with its own get and its own fallback:

async fn dashboard(session: Session) -> HandlerResult<Json<serde_json::Value>> {
    let user_id = match session.get::<i32>("user_id").await {
        Ok(Some(id)) => id,
        Ok(None) => return Err(AppError::Unauthorized),
        Err(_) => return Err(AppError::InternalError),
    };
    let name: String = session
        .get("name")
        .await
        .map_err(|_| AppError::InternalError)?
        .unwrap_or_else(|| "stranger".to_string());
    Ok(Json(serde_json::json!({ "id": user_id, "name": name })))
}

The user id is required, so a missing value is a 401. The name is optional, so a missing value falls back to "stranger". The two reads show the two attitudes a handler can take toward a missing value: refuse, or substitute a default. Which one fits depends on whether the handler can do its job without the value. A profile cannot work without knowing whose profile it is, so it refuses. A greeting can work with a placeholder, so it substitutes.

The Request Flow With an Extractor

The path of a request to the profile route, with the extractor in place, looks like this:

Browser sends request with cookie id=abc123
        |
        v
Session layer loads the session and puts it in the request extensions
        |
        v
Axum builds the handler arguments, Session comes from the extensions
        |
        v
Handler reads user_id with session.get
        |
        v
Handler loads the user from the database by that id
        |
        v
Handler returns the user as JSON

The extractor step sits between the layer and the handler body. Nothing in the handler body knows the cookie existed. If the extensions hold no session, the flow stops at the extractor step with a 500, and the handler body never runs. That ordering is why a missing layer shows up as a 500 instead of a 401: the failure happens before the handler gets its chance to answer.

Testing It

Three tests cover this page: the profile with a cookie, the profile without one, and the 500 that appears when the layer is missing. The first two run against the real application. The third builds a tiny router with a handler that takes a Session and no layer at all, which isolates the extractor failure. Add the tower crate as a development dependency:

Cargo.toml
[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
tests/session_test.rs
use axum::{
    Router,
    body::Body,
    http::{Request, StatusCode, header},
    routing::get,
};
use axum_project::app;
use serde_json::json;
use sqlx::PgPool;
use tower::ServiceExt;
use tower_sessions::Session;

const DATABASE_URL: &str = "postgres://axumdocs:axumdocs@127.0.0.1:5432/ch13_sessions";

async fn pool() -> PgPool {
    PgPool::connect(DATABASE_URL).await.unwrap()
}

fn login_request() -> Request<Body> {
    Request::builder()
        .method("POST")
        .uri("/login")
        .header(header::CONTENT_TYPE, "application/json")
        .body(Body::from(
            json!({"email": "ada@example.com", "password": "test-password-123"}).to_string(),
        ))
        .unwrap()
}

fn cookie_from(response: &axum::response::Response) -> String {
    let set_cookie = response
        .headers()
        .get(header::SET_COOKIE)
        .expect("login sets a cookie")
        .to_str()
        .unwrap()
        .to_string();
    set_cookie.split(';').next().unwrap().to_string()
}

#[tokio::test]
async fn me_with_cookie_returns_the_user() {
    let app = app(pool().await);
    let login = app.clone().oneshot(login_request()).await.unwrap();
    assert_eq!(login.status(), StatusCode::OK);
    let cookie = cookie_from(&login);

    let me = app
        .oneshot(
            Request::builder()
                .uri("/me")
                .header(header::COOKIE, &cookie)
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(me.status(), StatusCode::OK);
    let body = axum::body::to_bytes(me.into_body(), usize::MAX)
        .await
        .unwrap();
    assert_eq!(
        body.as_ref(),
        b"{\"id\":1,\"name\":\"Ada\",\"email\":\"ada@example.com\"}"
    );
}

#[tokio::test]
async fn me_without_cookie_is_401() {
    let response = app(pool().await)
        .oneshot(Request::builder().uri("/me").body(Body::empty()).unwrap())
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
    let body = axum::body::to_bytes(response.into_body(), usize::MAX)
        .await
        .unwrap();
    assert_eq!(body.as_ref(), b"{\"error\":\"unauthorized\"}");
}

async fn needs_session(session: Session) -> &'static str {
    let _ = session;
    "has a session"
}

#[tokio::test]
async fn session_extractor_without_layer_is_500() {
    let app = Router::new().route("/needs-session", get(needs_session));
    let response = app
        .oneshot(
            Request::builder()
                .uri("/needs-session")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
}

The first test logs in through the real login handler, pulls the cookie out of the login response, and sends it to the profile route. The cookie helper keeps only the id=... part of the Set-Cookie header, cutting it off at the first semicolon, because the attributes after it belong to the cookie's storage rules, not to the value the browser sends back. The second test calls the profile route with no cookie and expects the 401 with the shared body. The third test has no database and no login at all: a router with one handler that takes a Session and no layer, which must answer 500. Run all three with cargo test.

What the tests prove:

The three tests draw the line between the three outcomes a session read can have: a cookie that resolves to a user, no cookie at all, and no layer to provide a session. A handler that passes all three handles the read correctly in every state the application can be in.

Common Beginner Mistakes

Forgetting the layer

// Wrong - the handler asks for a Session, but no layer provides one
let app = Router::new()
    .route("/me", get(me))
    .with_state(pool);

The program compiles, starts, and serves the route. The first request to /me answers 500 with the message Can't extract session. Is 'SessionManagerLayer' enabled?. The fix is the .layer(session_layer) call, placed so it wraps the route. The same 500 appears when the layer is attached to a different router than the one holding the route, for example when the route lives on a sub-router that was merged before the layer was added. The layer must wrap the routes that use the session, not merely exist somewhere in the program.

A missing layer is a runtime error, not a compile error:

Rust cannot tell at compile time whether a router has the session layer attached. The program builds and starts before the mistake shows up as a 500 on the first request. Always test a session route with a real request after wiring the layer, instead of trusting a clean compile.

Unwrapping the read

// Wrong - a visitor who never logged in crashes the handler
let user_id = session.get::<i32>("user_id").await.unwrap().unwrap();

Two unwraps in one line, and either one can panic. The first panics when the stored value cannot be rebuilt as an i32. The second panics when the session is empty, which is the ordinary state of a visitor who never logged in. A panic in a handler turns into a 500 and drops the request, and it also writes a panic message to the server log for a situation that is not an error at all. The fix is the match at the top of this page: None becomes a 401, and only a genuine read failure becomes a 500.

Asking for the wrong type

// Wrong - login stored an i32, and this asks for a String
let user_id = session.get::<String>("user_id").await;

get rebuilds the stored JSON into the type asked for, and a number does not rebuild into a string. The call returns Err, and the handler answers 500 for a visitor who is properly logged in. The fix is to ask for the type that was inserted, i32 here, and to keep one type per key across the whole program. When a key's type needs to change, every insert and every get for that key must change together.

// Wrong - parsing the cookie yourself bypasses the layer
async fn me(headers: HeaderMap) -> HandlerResult<Json<User>> {
    let cookie = headers.get(header::COOKIE).unwrap().to_str().unwrap();
    // ... parse the id out of the text, look it up somewhere ...
}

A handler that parses the Cookie header itself is rebuilding what the layer already does, badly. It has to split the header text, find the right cookie by name, handle missing and malformed values, and then find the session record without the store the layer owns. Every one of those steps is a place to make a mistake, and the result duplicates the layer's work. The fix is the extractor: take Session as an argument and let the layer hand it over. If a handler needs something from the request that no extractor provides, that is the time to read a header by hand. A session is not that time.

Final Complete Example

Here is everything from this page in one place: the login that writes the session, the profile handler that reads it, the visit counter that reads and writes it, and the router that wires them together with the session layer.

src/lib.rs
pub mod errors;

use argon2::{
    Argon2,
    password_hash::{PasswordHash, PasswordVerifier},
};
use axum::{
    Json, Router,
    extract::State,
    routing::{get, post},
};
use errors::{AppError, HandlerResult};
use serde::{Deserialize, Serialize};
use sqlx::PgPool;
use tower_sessions::{Expiry, MemoryStore, Session, SessionManagerLayer};
use time::Duration;

#[derive(Debug, Serialize, sqlx::FromRow)]
pub struct User {
    pub id: i32,
    pub name: String,
    pub email: String,
}

#[derive(Debug, Deserialize)]
pub struct LoginInput {
    pub email: String,
    pub password: String,
}

#[derive(Debug, sqlx::FromRow)]
struct LoginRow {
    id: i32,
    password_hash: Option<String>,
}

pub fn app(pool: PgPool) -> Router {
    let session_store = MemoryStore::default();
    let session_layer = SessionManagerLayer::new(session_store)
        .with_secure(false)
        .with_expiry(Expiry::OnInactivity(Duration::days(7)));

    Router::new()
        .route("/login", post(login))
        .route("/me", get(me))
        .route("/visit", get(record_visit))
        .route("/public", get(public))
        .layer(session_layer)
        .with_state(pool)
}

async fn public() -> &'static str {
    "Anyone can read this."
}

fn password_matches(password: &str, stored_hash: &str) -> bool {
    let parsed = match PasswordHash::new(stored_hash) {
        Ok(parsed) => parsed,
        Err(_) => return false,
    };
    Argon2::default()
        .verify_password(password.as_bytes(), &parsed)
        .is_ok()
}

async fn login(
    State(pool): State<PgPool>,
    session: Session,
    Json(input): Json<LoginInput>,
) -> HandlerResult<Json<User>> {
    let row = sqlx::query_as::<_, LoginRow>(
        "SELECT id, password_hash FROM users WHERE email = $1",
    )
    .bind(&input.email)
    .fetch_optional(&pool)
    .await
    .map_err(|_| AppError::InternalError)?;

    let user_id = match row {
        Some(row) => match row.password_hash {
            Some(hash) if password_matches(&input.password, &hash) => row.id,
            _ => return Err(AppError::Unauthorized),
        },
        None => return Err(AppError::Unauthorized),
    };

    session
        .insert("user_id", user_id)
        .await
        .map_err(|_| AppError::InternalError)?;
    session
        .cycle_id()
        .await
        .map_err(|_| AppError::InternalError)?;

    let user = sqlx::query_as::<_, User>(
        "SELECT id, name, email FROM users WHERE id = $1",
    )
    .bind(user_id)
    .fetch_one(&pool)
    .await
    .map_err(|_| AppError::InternalError)?;

    Ok(Json(user))
}

async fn me(
    State(pool): State<PgPool>,
    session: Session,
) -> HandlerResult<Json<User>> {
    let user_id = match session.get::<i32>("user_id").await {
        Ok(Some(id)) => id,
        Ok(None) => return Err(AppError::Unauthorized),
        Err(_) => return Err(AppError::InternalError),
    };

    let user = sqlx::query_as::<_, User>(
        "SELECT id, name, email FROM users WHERE id = $1",
    )
    .bind(user_id)
    .fetch_optional(&pool)
    .await
    .map_err(|_| AppError::InternalError)?
    .ok_or(AppError::Unauthorized)?;

    Ok(Json(user))
}

async fn record_visit(
    session: Session,
) -> HandlerResult<Json<serde_json::Value>> {
    let visits: i32 = session
        .get("visits")
        .await
        .map_err(|_| AppError::InternalError)?
        .unwrap_or(0);
    session
        .insert("visits", visits + 1)
        .await
        .map_err(|_| AppError::InternalError)?;
    Ok(Json(serde_json::json!({ "visits": visits + 1 })))
}

Run it with cargo run and test it with cargo test. Log in, ask for /me with the cookie, and ask for it without. The two answers, a user and a 401, are the whole lesson: the session is read where it is used, and an empty session is a normal case with a proper answer.

Summary

The extractor turns the session from infrastructure into an argument. The handler does not fetch the session, parse a cookie, or call a store. It declares what it needs and uses what it gets. The discipline that follows from that is about the three outcomes of the read, and they deserve different answers: a stored id means a known visitor, a missing value means an unknown visitor and a 401, and a failed read means a bug and a 500. Once a handler answers those three cases correctly, it can trust the session for everything else it does, because the value it holds came from the server's own store under an id the client could not choose. That trust is what the next pages rely on: logout trusts it enough to delete the record, and the session check trusts it enough to guard a whole group of routes.