Logout by clearing session

Learn how session flush ends a login on the server, why that matters more than deleting the cookie, and what happens to the old cookie

Login creates a session. Reading the session proves who is asking. Logout ends the session, and ending it properly means ending it on the server, not just in the browser. This page is about that ending: calling session.flush() in a logout handler so the session record is deleted, the cookie stops working, and a copy of the old cookie cannot bring the login back.

Where This Fits

The session now has a full life: login writes the user id, handlers read it back, and the visitor stays logged in as long as the cookie keeps arriving. A life with a beginning and a middle needs an end. Without one, a login lasts until the session expires, which is seven days in this project, and a visitor on a shared computer stays logged in long after walking away. This page adds the end: a logout route that destroys the session on the spot.

Think of the coat check one last time. Login handed over the coat and took the ticket. Logout hands the ticket back and takes the coat. The attendant does not just throw the ticket away. The coat itself leaves the room. If the ticket alone were thrown away while the coat stayed on its hook, anyone holding a copy of the ticket could still claim it.

The Smallest Working Version

The logout handler below is three lines: flush the session, map a store failure to a 500, and answer 200. The login and profile handlers are included unchanged, because the proof that logout works is a profile request that stops working after it.

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,
    http::StatusCode,
    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("/logout", post(logout))
        .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))
}

async fn logout(session: Session) -> HandlerResult<StatusCode> {
    session
        .flush()
        .await
        .map_err(|_| AppError::InternalError)?;
    Ok(StatusCode::OK)
}

Start the server with cargo run, then run the whole life of a session in four requests, keeping the cookie between the first three:

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 -i -b cookies.txt -c cookies2.txt -X POST http://127.0.0.1:3000/logout
curl -b cookies.txt 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"}
HTTP/1.1 200 OK
set-cookie: id=; HttpOnly; SameSite=Strict; Path=/; Max-Age=0
{"error":"unauthorized"}

The first two requests are the login and a profile read that works. The third is the logout, and its response carries a Set-Cookie header that tells the browser to delete the cookie: the value is empty, and Max-Age=0 means the cookie is already expired. The fourth request sends the old cookie from the saved file anyway, and the server answers 401, because the session record is gone and the old id resolves to nothing. Logging out with no cookie at all also answers 200, because flushing a session that never existed is a harmless no-op.

Working Setup:

If the profile answers 200 before logout and 401 after it, with the same cookie file, logout works. The old cookie stopping is the proof: the server deleted the record, and no copy of the id can bring it back.

What flush Does

flush does three things at once, and the combination is what makes it the right call for logout. It removes all data from the session, it deletes the session record from the store, and it drops the session id, so the Session value has no id left at all. The crate's own description of the method is exactly that: flush removes all data contained in the session and then deletes it from the store.

Each part matters on its own. Removing the data means the user id is gone from the in-memory copy the handler holds. Deleting the record means the store no longer has anything under that id, so the next request that presents the id finds nothing to load. Dropping the id means the session object itself is empty afterwards: a later insert in the same request would start a brand new session instead of reviving the old one. The layer then sends the removal cookie, the Set-Cookie header with an empty value and Max-Age=0, which tells the browser to throw its copy away too.

The handler maps a flush failure to InternalError. A store that cannot delete is a server problem, and answering 500 is honest: the visitor asked to log out, and the server could not do it. In practice the failure is rare with the memory store, but the mapping belongs in the handler so a real store failure is never silently reported as a success.

The Four Ways to Empty a Session

flush is one of four methods that remove session data, and they differ in what survives. Knowing the differences keeps logout from being confused with the other three.

MethodData in memoryRecord in the storeSession id
remove("user_id")One key gone, the rest staysStill there, saved at the end of the requestStill valid
clear()All data gone from the copy the handler holdsStill there until the next saveStill valid
delete()Still there for the rest of the requestGoneStill held by the session object
flush()All goneGoneDropped

remove drops a single value, which fits forgetting one fact, such as a stored display name, while the login stays alive. clear empties the data the handler sees, but the id stays valid, so the same cookie still identifies a live, empty session on the next request. delete removes the record from the store, but the in-memory copy keeps its data until the request ends, so code later in the same handler can still read values that no longer exist in the store. flush is the only one that does all three: data gone, record gone, id gone. That is why logout uses flush and nothing else. The other three are tools for other jobs, and using one of them as logout leaves something behind: a valid id, a live record, or readable data.

Clear is not logout:

clear() empties the data and feels like a logout, but the session id stays valid. The next request with the same cookie loads a live, empty session, and anything the application stores into sessions by default after that point would land in a session whose id was never retired. Ending a login means retiring the id, and only flush does that.

Why the Server Side Matters More Than the Browser

A session has two halves: the record on the server and the cookie in the browser. Logout can act on either half, but only one of them decides whether the login still works. Deleting the cookie in the browser removes the visitor's own copy of the id. The record stays in the store, alive until it expires, and anyone holding a copy of the id can still present it and be treated as the logged-in user. A cookie is easy to copy: it sits in browser storage, in logs, in a stolen laptop, in a request an attacker recorded. Deleting the browser's copy does nothing about the other copies.

Deleting the record on the server ends the login for every copy at once. The id becomes a pointer to nothing. The next request that presents it loads no session, the handler finds no user id, and the answer is 401. That is what the fourth curl above proved: the same cookie file, sent again after logout, no longer works. The removal cookie the layer sends is still useful, because it cleans up the browser's own copy, but it is the cleanup, not the logout. The logout is the delete on the server.

The same reasoning explains why logout must work even when the visitor's browser is gone. A logout request from a phone ends the session for the laptop too, because the record is shared and the cookie is not. The server is the one place where all copies of the id meet, so it is the one place where ending the session is final.

Logout Is Per Session, Not Per User

One detail of flush surprises beginners, and it is better to meet it here than in production. flush ends this session, the one tied to the cookie on this request. It does not end the user's other sessions. A visitor logged in on a laptop and on a phone has two sessions with two ids and two records. Logging out on the laptop flushes the laptop's record. The phone's record is untouched, and the phone stays logged in.

That is usually the right behaviour: the visitor asked to log out of this device, not of every device they own. A "log out everywhere" button is a different feature. It needs a way to find all of a user's sessions, which means the application must keep its own mapping from user id to session ids, because the session store itself is keyed by session id and cannot answer that question. The mapping, and the loop that flushes each session in it, belong to the application's own code, not to this handler. What this page's handler guarantees is narrower and exactly what most logouts need: this session ends, now, completely.

Logging out everywhere needs a mapping the store does not have:

The session store answers one question: what data belongs to this session id. It cannot answer the reverse question, which sessions belong to this user. An application that needs "log out everywhere" keeps its own record of that, usually a small table mapping user ids to session ids, written at login and read at logout. Without that record, there is no list of sessions to end.

The Logout Request Flow

The path of a logout request, from the browser to the store and back, looks like this:

Browser posts to /logout with cookie id=abc123
        |
        v
Session layer loads the session for id abc123
        |
        v
Handler calls session.flush()
        |
        v
Session data is cleared and the record is deleted from the store
        |
        v
Session id is dropped, so the session is empty
        |
        v
Layer sends a removal cookie, Max-Age=0, in the response
        |
        v
Browser deletes its cookie, and the old id resolves to nothing

The handler itself does one thing in the middle of that flow. The layer does the loading before it and the removal cookie after it. The browser does the last step, deleting its copy when told. The server never trusts the browser to have done its part: the next request is checked against the store, not against the browser's word.

A Richer Example - Logout With a Message

The smallest logout answers with an empty 200, which is the right shape for a client that only checks the status. A client that shows a message wants a body to display. Returning JSON with a message changes one line of the handler and nothing else:

src/lib.rs
async fn logout(session: Session) -> HandlerResult<Json<serde_json::Value>> {
    session
        .flush()
        .await
        .map_err(|_| AppError::InternalError)?;
    Ok(Json(serde_json::json!({ "message": "logged out" })))
}

The response is status 200 with the body {"message":"logged out"}, and the removal cookie travels in the header exactly as before. The flush call is unchanged, which is the point: the body is presentation, and the logout is the flush. A frontend that reads the message can show it, and a client that only checks the status can ignore the body. Either way, the session ends the same way.

Testing It

Two tests cover this page. The first runs the whole life of a session: log in, read the profile, log out, and read the profile again with the same cookie. The second logs out without any cookie at all and expects success. Add the tower crate as a development dependency:

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

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 full_flow_login_me_logout_me() {
    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
        .clone()
        .oneshot(
            Request::builder()
                .uri("/me")
                .header(header::COOKIE, &cookie)
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(me.status(), StatusCode::OK);

    let logout = app
        .clone()
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/logout")
                .header(header::COOKIE, &cookie)
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(logout.status(), StatusCode::OK);

    let me_again = app
        .oneshot(
            Request::builder()
                .uri("/me")
                .header(header::COOKIE, &cookie)
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(me_again.status(), StatusCode::UNAUTHORIZED);
}

#[tokio::test]
async fn logout_without_a_session_still_succeeds() {
    let response = app(pool().await)
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/logout")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::OK);
}

The first test clones the router for each request, because oneshot consumes the router it is called on. It logs in, reads the profile with the cookie, logs out with the same cookie, and reads the profile again with the same cookie. The last assertion is the one that matters: the old cookie must answer 401 after logout, which proves the record is gone rather than merely hidden. The second test posts to logout with no cookie and expects 200. Flushing a session that never existed is a no-op, so logout never fails for a visitor who is already logged out. Run both with cargo test.

What the tests prove:

The pair of tests pins down the two halves of logout: the old cookie stops working, and a missing cookie is not an error. A logout that passes both ends the session on the server and never punishes a visitor who was already out.

Common Beginner Mistakes

// Wrong - this runs in the browser and only removes the local copy
document.cookie = "id=; Max-Age=0; Path=/";

This line deletes the cookie from the browser that runs it. The session record stays in the store, alive until it expires, and any copy of the id still works. A visitor who "logs out" this way on a shared computer leaves a live session behind for the next person at the keyboard, as long as that person can find the id in the browser history, the logs, or a recorded request. The fix is the server-side handler at the top of this page: the browser deletes its copy because the server told it to, after the server already deleted the record. The removal cookie is the last step of logout, never the first.

Removing the user id and calling it logout

// Wrong - the session id stays valid, and the session stays alive
async fn logout(session: Session) -> HandlerResult<StatusCode> {
    session
        .remove("user_id")
        .await
        .map_err(|_| AppError::InternalError)?;
    Ok(StatusCode::OK)
}

This handler drops the user id, so the profile route would answer 401 afterwards, and it looks like a logout. The session itself is still alive: the id is still valid, the record is still in the store, and any other data in the session is still there. A session id that stays valid after "logout" is an id that can be reused, and any code that stores a fresh value into the session under that id would revive it without a login. The fix is flush, which retires the id along with the data. remove is for dropping one value from a live session. flush is for ending the session.

Answering 401 from logout when there is no session

// Wrong - logout should succeed even when nobody is logged in
async fn logout(session: Session) -> HandlerResult<StatusCode> {
    match session.get::<i32>("user_id").await {
        Ok(Some(_)) => {
            session.flush().await.map_err(|_| AppError::InternalError)?;
            Ok(StatusCode::OK)
        }
        _ => Err(AppError::Unauthorized),
    }
}

This handler checks for a user id first and refuses to log out when there is none. That turns a harmless repeat logout, a double-clicked button, or a logout after the session already expired into an error for the visitor. Logout is not a guarded action. It is the act of ending a session, and ending a session that does not exist is already done. The fix is to call flush without checking first. flush on an empty session does nothing and returns success, which is the correct answer for a visitor who is already logged out.

Logout must never require a login:

A logout route that answers 401 when there is no session creates a trap: a visitor whose session expired cannot log out, and a client that logs out after every session end sees errors for an action that already succeeded. Keep logout open, keep it simple, and let flush handle the empty case.

Forgetting that logout needs the layer too

The logout handler takes a Session, so it needs the session layer exactly like the profile handler does. A router that serves /logout without the layer wrapping it gives the same 500 the profile route gives: Can't extract session. Is 'SessionManagerLayer' enabled?. The fix is the same: the .layer(session_layer) call must wrap the logout route. In the router at the top of this page the layer is attached to the whole router, so every route, including logout, is wrapped. If the routes are ever split into separate routers, the logout route must stay on the side that has the layer.

Final Complete Example

Here is everything from this page in one place: the login that writes the session, the profile handler that reads it, and the logout handler that ends it.

src/lib.rs
pub mod errors;

use argon2::{
    Argon2,
    password_hash::{PasswordHash, PasswordVerifier},
};
use axum::{
    Json, Router,
    extract::State,
    http::StatusCode,
    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("/logout", post(logout))
        .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))
}

async fn logout(session: Session) -> HandlerResult<StatusCode> {
    session
        .flush()
        .await
        .map_err(|_| AppError::InternalError)?;
    Ok(StatusCode::OK)
}

Run it with cargo run and test it with cargo test. Log in, read the profile, log out, and read the profile again with the same cookie. The 401 on the last request is the whole page in one status code: the session is over, on the server, for every copy of the cookie.

Summary

Logout is a delete, not a suggestion. The browser can be told to forget the cookie, and it usually will, but the server cannot rely on that, because the browser is not the only place the cookie lives. The record is the session, and the cookie is only a pointer to it. flush deletes the record, clears the data, and drops the id, which is the complete ending: nothing remains that a replayed cookie could resolve to. The decision that follows is about scope: remove drops one value from a live session, clear empties the data but keeps the id, and flush ends the session entirely. A logout button that calls flush unconditionally, without checking for a session first, is a logout that works on the first click, on a repeat click, and on a session that already expired. That reliability is the point: ending a login should be the easiest thing in the application to do, and the hardest thing to get wrong.