tower-sessions crate
Learn what the tower-sessions crate provides, how a session store keeps session data, and how to wire SessionManagerLayer onto an Axum router
HTTP on its own remembers nothing. Every request arrives as a stranger, with no link to the request before it. A session is the fix for that forgetfulness: a small record the server keeps for one visitor, found again on every later request. The tower-sessions crate provides sessions as Tower middleware for Axum. It gives you three things in one package: a layer that manages the session for every request, a store that holds the session data, and a Session value your handlers use to read and write that data.
Where This Fits
A login handler checks a password once, and then the server needs to remember the result. Without a session, the visitor would have to send the password again on every single request, and the server would have to check it again every time. That is slow, and it puts the password on the wire far more often than it needs to be there. This page adds the piece that remembers: the crate that stores a small record per visitor and hands it back on each request. Later pages use that record to keep a login alive, to read it inside handlers, to end it on logout, and to guard routes with it.
Think of a coat check at a restaurant. You hand over your coat once and receive a numbered ticket. The ticket itself is not your coat, and it says nothing about who you are. On the way out you show the ticket, the attendant finds your coat by the number, and hands it back. The cookie is the ticket. The session store is the room full of coats. The layer is the attendant who takes the ticket, finds the coat, and returns it.
The Smallest Working Version
The crate's own counter example is the smallest program that shows sessions working. A visitor loads the page, the handler reads a number from the session, adds one, and stores it back. The first visit shows 0, the second shows 1, the third shows 2. A visitor without the cookie always sees 0, because the server has no ticket to find their number by.
Create a project with this Cargo.toml:
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8.9"
tokio = { version = "1.54.1", features = ["full"] }
tower-sessions = "0.15"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
time = "0.3"
The time crate is there for one reason: the expiry settings below measure durations with time::Duration, so the project needs it as a direct dependency. Then write the whole program in one file:
use std::net::SocketAddr;
use axum::{response::IntoResponse, routing::get, Router};
use serde::{Deserialize, Serialize};
use time::Duration;
use tower_sessions::{Expiry, MemoryStore, Session, SessionManagerLayer};
const COUNTER_KEY: &str = "counter";
#[derive(Default, Deserialize, Serialize)]
struct Counter(usize);
async fn handler(session: Session) -> impl IntoResponse {
let counter: Counter = session
.get(COUNTER_KEY)
.await
.unwrap()
.unwrap_or_default();
session
.insert(COUNTER_KEY, counter.0 + 1)
.await
.unwrap();
format!("Current count: {}", counter.0)
}
#[tokio::main]
async fn main() {
let session_store = MemoryStore::default();
let session_layer = SessionManagerLayer::new(session_store)
.with_secure(false)
.with_expiry(Expiry::OnInactivity(Duration::seconds(10)));
let app = Router::new().route("/", get(handler)).layer(session_layer);
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
let listener = tokio::net::TcpListener::bind(&addr).await.unwrap();
axum::serve(listener, app.into_make_service())
.await
.unwrap();
}
Run it with cargo run, then ask for the page four times with curl, keeping the cookie between the first three requests:
curl -c cookies.txt http://127.0.0.1:3000/
curl -b cookies.txt http://127.0.0.1:3000/
curl -b cookies.txt http://127.0.0.1:3000/
curl http://127.0.0.1:3000/
The output is:
Current count: 0
Current count: 1
Current count: 2
Current count: 0
The first three requests share one cookie, so the server finds the same session each time and the number climbs. The fourth request sends no cookie, so the server starts a fresh session and the count is 0 again. The curl flags do the cookie work here: -c cookies.txt saves the cookie the server sets into a file, and -b cookies.txt sends the saved cookie back on the next request. A browser does the same thing automatically.
Working Setup:
If the count climbs 0, 1, 2 with the cookie file and restarts at 0 without it, the layer is wired up correctly. The session store is holding data between requests, and the cookie is carrying the session id back to the server.
Understanding the Pieces
The small program has five moving parts, and each one does a different job. They are worth separating, because every later page uses them by name.
MemoryStore
let session_store = MemoryStore::default();
A store is where session data lives between requests. MemoryStore keeps it in a hash map in the server's own memory. A hash map is a collection that finds a value by its key, and here the key is the session id and the value is the session's record. MemoryStore::default() builds an empty one. It is the simplest store the crate ships, it needs no setup, and it is the right store for learning. It has two limits a beginner must know: restarting the server wipes every session, and two servers running at once do not share it. A visitor whose requests land on different servers would lose their session. The crate's answer to that is a different store, covered below.
SessionManagerLayer
let session_layer = SessionManagerLayer::new(session_store)
.with_secure(false)
.with_expiry(Expiry::OnInactivity(Duration::seconds(10)));
SessionManagerLayer is the middleware itself. A layer is a reusable piece that wraps a service and adds behaviour around it, and this layer adds session behaviour around your routes. SessionManagerLayer::new takes the store and returns the layer with the crate's default cookie settings. The two builder calls after it change two of those settings.
.with_secure(false) turns off the Secure flag on the session cookie. A cookie marked Secure is only sent by browsers over HTTPS, which is encrypted HTTP. On a local development server running plain http://127.0.0.1:3000, a browser would never send a Secure cookie back, so the session would never be found and every request would look like a first visit. Setting it to false is correct for local development only. A server reached over HTTPS must leave it on, and the default is on, which is the safe choice.
.with_expiry(Expiry::OnInactivity(Duration::seconds(10))) says a session expires after ten seconds without a change. Expiry is the rule for when a session stops being valid. OnInactivity measures from the last time the session was modified, and reading a session does not count as activity. Ten seconds is deliberately short for this example, so the behaviour is easy to watch: wait eleven seconds, ask again with the same cookie, and the count is back at 0 because the old session expired. The other expiry choices are covered in their own section below.
Attaching the layer
let app = Router::new().route("/", get(handler)).layer(session_layer);
The .layer call attaches the session layer to the router. The route is added first, then the layer, so the layer wraps that route. Every request to the route passes through the layer before it reaches the handler, and every response passes back through it on the way out. That round trip is where the session work happens: the layer reads the cookie, loads the session from the store, hands it to the handler, and saves it again when the handler finishes. Without this line, the layer is just an unused value and no session exists at all.
The Session extractor
async fn handler(session: Session) -> impl IntoResponse {
Session as a handler argument is an extractor. An extractor is a function argument that Axum fills in from the incoming request instead of the caller passing it. The layer places the loaded session into the request before the handler runs, and the extractor picks it out. The handler never parses a cookie header and never talks to the store directly. It just uses the Session value.
insert and get
let counter: Counter = session
.get(COUNTER_KEY)
.await
.unwrap()
.unwrap_or_default();
session
.insert(COUNTER_KEY, counter.0 + 1)
.await
.unwrap();
get reads a value by its key, and insert writes a value under a key. Both are async, so both need .await, because they may talk to a store that lives across a network. get returns a Result<Option<T>>, which is three cases in one type: an error reading the store, no value stored under that key, or a value of the type asked for. The .unwrap() on the Result turns a store error into a panic, which is acceptable in this tiny example and not in real code. The .unwrap_or_default() on the Option turns a missing value into Counter(0), which is how the first visit gets its starting number. The Counter type itself is a tuple struct holding one usize, a non-negative whole number, and it derives Default, Deserialize, and Serialize so it can be stored as JSON and rebuilt from it. The key is a plain string, "counter", kept in a constant so every use spells it the same way.
Insert and get must agree on the type:
insert stores any value that can be turned into JSON, and get rebuilds it into the type you ask for. If you store a number under a key and later ask for a string under the same key, get returns an error instead of a value. Pick one type per key and keep it the same everywhere that key is used.
How a Session Store Works
A session is made of three pieces, and keeping them apart is the whole idea. The first piece is the cookie, which holds only the session id as its value. The second piece is an in-memory map of keys and values, which is the API the handler sees. The third piece is the session store, where the session data is kept between requests. The handler reads and writes the map. The layer moves the map into and out of the store. The cookie only says which record to load.
The store is a trait, which is a Rust interface that says what operations a type must provide. The SessionStore trait has four operations: create makes a new record, save writes a record, load reads a record by its id, and delete removes a record. MemoryStore implements the trait with a hash map. Any other type that implements the same four operations can be dropped in as the store without changing the layer or the handlers. That split is what makes the store pluggable: the session logic never knows or cares where the data lives.
The layer saves a session only when it changed. After the handler returns, the layer checks whether the session was modified, and if it was, it calls save on the store. A request that only reads the session writes nothing back. That is why the counter example saves on every visit, because every visit inserts a new number, while a handler that only reads a stored name causes no write at all.
A session also has a lifetime on the store side. By default, sessions are considered expired after two weeks. An expired session is not loaded even if the browser still sends its cookie: the layer treats it as if no session existed and starts a fresh one. The with_expiry setting changes that rule, and stores that keep data in a database need old records cleaned up on a schedule, which is covered in the expiry section below.
The cookie never holds your data:
Only the session id travels in the cookie. The values you insert, the user id, the name, the count, stay on the server inside the store. Anyone who reads the cookie sees a random-looking id and nothing else. That is a deliberate security property, not an accident of the design.
Why the Crate Splits Storage From the Cookie
An earlier design for sessions put all the data inside the cookie itself. That design has a hard limit: a cookie can only hold a small amount of text, and everything in it travels on every request. A session with a shopping basket or a long list of permissions would make every request bigger and slower, and the data would be visible to anyone who could read the cookie.
Splitting storage from the cookie avoids both problems. The cookie stays tiny, one id, no matter how much data the session holds. The data stays on the server, where it can be as large as the store allows and where it can be deleted in one place. Deleting the server record ends the session everywhere at once, even if copies of the cookie still exist. That single fact is what makes logout reliable, and it is the reason the rest of this cluster builds on this crate instead of stuffing data into cookies.
A Richer Example - Remembering a Name
The counter shows one handler using one value. Real use needs several handlers sharing several values through the same session. This example adds two routes to the same program: one that stores a name, and one that greets the visitor by it. The session layer is built once and shared by all three routes.
use std::net::SocketAddr;
use axum::{Json, Router, response::IntoResponse, routing::get, routing::post};
use serde::{Deserialize, Serialize};
use time::Duration;
use tower_sessions::{Expiry, MemoryStore, Session, SessionManagerLayer};
const COUNTER_KEY: &str = "counter";
#[derive(Default, Deserialize, Serialize)]
struct Counter(usize);
async fn counter(session: Session) -> impl IntoResponse {
let counter: Counter = session
.get(COUNTER_KEY)
.await
.unwrap()
.unwrap_or_default();
session
.insert(COUNTER_KEY, counter.0 + 1)
.await
.unwrap();
format!("Current count: {}", counter.0)
}
#[derive(Deserialize)]
struct NameInput {
name: String,
}
async fn remember_name(
session: Session,
Json(input): Json<NameInput>,
) -> impl IntoResponse {
session.insert("name", input.name).await.unwrap();
"Name remembered."
}
async fn greet(session: Session) -> impl IntoResponse {
match session.get::<String>("name").await {
Ok(Some(name)) => format!("Hello, {name}!"),
_ => "Hello! I do not know your name yet.".to_string(),
}
}
#[tokio::main]
async fn main() {
let session_store = MemoryStore::default();
let session_layer = SessionManagerLayer::new(session_store)
.with_secure(false)
.with_expiry(Expiry::OnInactivity(Duration::days(7)));
let app = Router::new()
.route("/", get(counter))
.route("/remember-name", post(remember_name))
.route("/greet", get(greet))
.layer(session_layer);
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
let listener = tokio::net::TcpListener::bind(&addr).await.unwrap();
axum::serve(listener, app.into_make_service())
.await
.unwrap();
}
remember_name takes a JSON body with a name field and stores it under the key "name". Json is the extractor that reads a JSON request body into a Rust struct, and NameInput is that struct. The handler stores a String, which is a different type from the Counter stored under "counter", and that is fine because each key has its own type. greet reads the name back with get::<String>, and the match handles the missing case by greeting a stranger instead. The expiry here is seven days of inactivity instead of ten seconds, because a remembered name should last longer than a demo counter.
Try it with curl, keeping the cookie between requests:
curl -c cookies.txt -X POST http://127.0.0.1:3000/remember-name -H 'Content-Type: application/json' -d '{"name":"Ada"}'
curl -b cookies.txt http://127.0.0.1:3000/greet
curl http://127.0.0.1:3000/greet
The output is:
Name remembered.
Hello, Ada!
Hello! I do not know your name yet.
The second request sends the cookie, so the server finds the session and the stored name. The third request sends no cookie, so the server starts a fresh session with no name. Two different handlers, one shared session, and neither handler knows about the other. The session is the only thing they share.
Changing the Cookie Settings
The layer's builder methods tune the cookie the browser receives. Each one changes a single attribute, and each has a default that is safe for a server reached over HTTPS. The settings below are the ones beginners reach for first.
let session_layer = SessionManagerLayer::new(session_store)
.with_name("session-id")
.with_http_only(true)
.with_same_site(SameSite::Lax)
.with_secure(false)
.with_path("/")
.with_always_save(true);
with_name changes the cookie's name from the default "id" to something else. The default name is deliberately plain, because a distinctive cookie name tells an attacker which session library the server uses. Renaming it is fine, but it buys little on its own, and the rest of the program never mentions the name, so changing it changes nothing in the handlers.
with_http_only(true) marks the cookie HttpOnly, which means JavaScript running in the browser cannot read it. That matters because a script injected into the page by an attacker could otherwise steal the session id. The default is true, and there is no good reason to turn it off.
with_same_site sets the SameSite attribute, which controls when the browser sends the cookie on requests that come from another site. SameSite is imported from tower_sessions::cookie. The default is Strict, which means the browser only sends the cookie on requests that start on your own site. Lax is looser: the browser also sends it when the visitor follows an ordinary link from another site to yours. Strict is safer against a class of attacks where another site tricks the browser into making a request to yours, and it is the default for that reason. Lax fits sites where visitors often arrive by following links.
with_secure was covered above: true on HTTPS, false for local development over plain HTTP. with_path("/") says the cookie is sent on every path of the site, which is the default and the usual choice. with_always_save(true) makes the layer save the session at the end of every request, even when nothing changed. The default is false, which skips the write when nothing changed, and that is the better default: it avoids pointless work on every read-only request.
Secure cookies and local development:
The default layer marks the cookie Secure. That is correct for a server reached over HTTPS, and wrong for a local server over plain HTTP. If the counter restarts at 0 on every request even though the browser or curl is sending the cookie back, check this setting first. curl does not enforce the Secure rule, so the bug only shows up in a real browser, which makes it easy to miss during testing.
Choosing How Long a Session Lives
Expiry is set with with_expiry, and there are three choices. Each one answers a different question about when a session should stop working.
Expiry::OnSessionEnd ties the session to the browser session: when the visitor closes the browser, the cookie goes away with it. The server record still expires by the two-week default, but the browser stops presenting the id. This fits logins on shared computers, where leaving the browser open is the risk.
Expiry::OnInactivity(Duration) ends the session after a period with no changes, which is the choice used in both examples above. Ten seconds shows the behaviour quickly. Seven days is a realistic value for a remembered login. Reading the session does not reset the clock, only writing to it does, so a visitor who keeps reading but never changes anything will still be logged out when the time runs out.
Expiry::AtDateTime ends the session at one fixed moment, no matter how active the visitor is. It takes an OffsetDateTime, a date and time with a time zone, from the time crate:
let session_layer = SessionManagerLayer::new(session_store)
.with_secure(false)
.with_expiry(Expiry::AtDateTime(
OffsetDateTime::now_utc() + Duration::days(30),
));
This fits sessions that must end on a known date, such as a trial that lasts thirty days. A single session can also change its own expiry while handling a request, with session.set_expiry, which takes an Option<Expiry> and applies from that moment on.
One more detail belongs here. Stores that keep data in a database, such as the SQLx stores below, do not delete expired records by themselves. Expired records pile up until something removes them, so those stores offer a background task that deletes expired sessions on a schedule. MemoryStore does not need that task, because its records disappear with the server process anyway.
Other stores for other needs:
MemoryStore is the built-in store and the right one for learning. When sessions must survive a restart or be shared across servers, the crate's ecosystem has persistent stores: a Redis store, SQLx stores for SQLite, Postgres, and MySQL, and a MongoDB store, each in its own crate. They all implement the same SessionStore trait, so swapping the store means changing the SessionManagerLayer::new argument and nothing else in the handlers. The SQLx stores need a table for the session records and a background task to delete expired ones, which is why this page stays with the memory store.
What Happens When a Request Arrives
The layer does four things on every request, in this order. The diagram shows the flow for a request that carries a session cookie:
Browser sends request with cookie id=abc123
|
v
SessionManagerLayer reads the cookie
|
v
Store loads the record for id abc123
|
v
Session is placed on the request
|
v
Handler reads and writes values with insert and get
|
v
Layer saves the session if it changed
|
v
Response goes back, with a Set-Cookie header when the id is new
When the request carries no cookie, or the id has no record, the layer builds an empty session instead of failing. The handler sees an empty session and behaves accordingly, usually by treating the visitor as unknown. When the handler inserts a value, the layer creates a fresh id, saves the record under it, and sends the id back in a Set-Cookie header. The browser stores that cookie and sends it on the next request, which closes the loop.
Testing It
A test can prove the session works without starting a server or opening a browser. The oneshot method from the tower crate sends one mock request straight through the router, and the test reads the cookie out of the first response and sends it back on the second request. Add the tower crate as a development dependency:
[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
Then write the test:
use axum::{
Router,
body::Body,
http::{Request, StatusCode, header},
response::IntoResponse,
routing::get,
};
use tower::ServiceExt;
use tower_sessions::{MemoryStore, Session, SessionManagerLayer};
const COUNTER_KEY: &str = "counter";
async fn counter(session: Session) -> impl IntoResponse {
let count: usize = session
.get(COUNTER_KEY)
.await
.unwrap()
.unwrap_or(0);
session.insert(COUNTER_KEY, count + 1).await.unwrap();
format!("Current count: {count}")
}
fn cookie_from(response: &axum::response::Response) -> String {
let set_cookie = response
.headers()
.get(header::SET_COOKIE)
.expect("a cookie is set")
.to_str()
.unwrap()
.to_string();
set_cookie.split(';').next().unwrap().to_string()
}
#[tokio::test]
async fn counter_increments_only_with_the_cookie() {
let app = Router::new()
.route("/", get(counter))
.layer(
SessionManagerLayer::new(MemoryStore::default())
.with_secure(false),
);
let first = app
.clone()
.oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(first.status(), StatusCode::OK);
let cookie = cookie_from(&first);
let body = axum::body::to_bytes(first.into_body(), usize::MAX)
.await
.unwrap();
assert_eq!(body.as_ref(), b"Current count: 0");
let second = app
.clone()
.oneshot(
Request::builder()
.uri("/")
.header(header::COOKIE, &cookie)
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
let body = axum::body::to_bytes(second.into_body(), usize::MAX)
.await
.unwrap();
assert_eq!(body.as_ref(), b"Current count: 1");
let fresh = app
.oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
.await
.unwrap();
let body = axum::body::to_bytes(fresh.into_body(), usize::MAX)
.await
.unwrap();
assert_eq!(body.as_ref(), b"Current count: 0");
}
The test builds the same router the program uses, with the same layer. The first request has no cookie and gets Current count: 0, and the helper pulls the Set-Cookie value out of the response, keeping only the id=... part before the first semicolon. The second request sends that cookie back and gets Current count: 1, which proves the session survived between requests. The third request has no cookie and gets Current count: 0 again, which proves the count belongs to the session, not to the server as a whole. The router is cloned for each request because oneshot consumes the router it is called on, and Router implements Clone cheaply. Run it with cargo test, and all three assertions must pass for the session wiring to be correct.
What a passing test proves:
A passing counter test proves three things at once: the layer is attached, the store holds data between requests, and the cookie round trip works. If the second request returned 0, the layer would be missing or the cookie would not be reaching the server, and the test would point at the wiring instead of at the handler.
Common Beginner Mistakes
Forgetting to attach the layer
// Wrong - the handler asks for a Session, but no layer provides one
let app = Router::new().route("/", get(handler));
The handler compiles fine, because Session as an extractor is always a valid argument type. At runtime, the extractor finds no session on the request and rejects with status 500 and the message Can't extract session. Is 'SessionManagerLayer' enabled?. The fix is the .layer(session_layer) call on the router. The error message names the fix directly, so when this 500 appears, the layer is the first thing to check.
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, starts, and serves the first request before the mistake shows up as a 500. Always test a session route with a real request after wiring the layer, instead of trusting a clean compile.
Leaving the Secure flag on during local development
// Wrong for local development - the browser never sends this cookie back
let session_layer = SessionManagerLayer::new(session_store);
With the defaults, the cookie carries the Secure flag. A browser on plain http://127.0.0.1:3000 will store the cookie but will not send it back over an unencrypted connection, so every request looks like a first visit and the counter never climbs past 0. The fix is .with_secure(false) while developing locally, and removing that call before deploying to a server reached over HTTPS. The trap is that curl does not enforce the Secure rule, so the same program can look correct in curl and broken in a browser.
Expecting the memory store to survive a restart
MemoryStore lives in the server process. Stopping the server with Ctrl+C and starting it again wipes every session, and every visitor has to start over. That is expected behaviour for this store, not a bug. During development it is harmless. In production it means a deploy logs everyone out, which is why a persistent store is the right choice once sessions must survive restarts.
Storing secrets in the session
// Wrong - never store a password, or anything like one, in a session
session.insert("password", input.password).await.unwrap();
The session data lives on the server, so it feels safe, but it is still the wrong place for a password. A password in the store is a password that can leak from a backup, a log, or a database dump, and it serves no purpose: the password was already checked at login, and only the user id needs remembering. Store the user id and nothing secret. The same rule covers API keys, tokens, and anything else that would let someone act as the user if it leaked.
Final Complete Example
Here is everything from this page in one program: the counter, the name handlers, and the session layer with a seven-day inactivity expiry.
use std::net::SocketAddr;
use axum::{Json, Router, response::IntoResponse, routing::get, routing::post};
use serde::{Deserialize, Serialize};
use time::Duration;
use tower_sessions::{Expiry, MemoryStore, Session, SessionManagerLayer};
const COUNTER_KEY: &str = "counter";
#[derive(Default, Deserialize, Serialize)]
struct Counter(usize);
async fn counter(session: Session) -> impl IntoResponse {
let counter: Counter = session
.get(COUNTER_KEY)
.await
.unwrap()
.unwrap_or_default();
session
.insert(COUNTER_KEY, counter.0 + 1)
.await
.unwrap();
format!("Current count: {}", counter.0)
}
#[derive(Deserialize)]
struct NameInput {
name: String,
}
async fn remember_name(
session: Session,
Json(input): Json<NameInput>,
) -> impl IntoResponse {
session.insert("name", input.name).await.unwrap();
"Name remembered."
}
async fn greet(session: Session) -> impl IntoResponse {
match session.get::<String>("name").await {
Ok(Some(name)) => format!("Hello, {name}!"),
_ => "Hello! I do not know your name yet.".to_string(),
}
}
#[tokio::main]
async fn main() {
let session_store = MemoryStore::default();
let session_layer = SessionManagerLayer::new(session_store)
.with_secure(false)
.with_expiry(Expiry::OnInactivity(Duration::days(7)));
let app = Router::new()
.route("/", get(counter))
.route("/remember-name", post(remember_name))
.route("/greet", get(greet))
.layer(session_layer);
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
let listener = tokio::net::TcpListener::bind(&addr).await.unwrap();
axum::serve(listener, app.into_make_service())
.await
.unwrap();
}
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8.9"
tokio = { version = "1.54.1", features = ["full"] }
tower-sessions = "0.15"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
time = "0.3"
[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
Run it with cargo run and test it with cargo test. The counter proves the session round trip works, the name handlers prove several handlers can share one session, and the seven-day expiry gives remembered data a realistic lifetime.
Summary
The crate's split is the idea to carry forward: the cookie is only a ticket, the store holds the coats, and the layer is the attendant moving between them. That split is what keeps the cookie tiny, the data off the wire, and logout a single server-side delete. The decision that follows from it is about the store, not the handlers. Use MemoryStore while learning and while a single server process is enough, because it needs no setup and the handlers never notice the difference. Move to a persistent store when sessions must survive a restart or be shared across servers, and change only the argument to SessionManagerLayer::new, because the trait boundary keeps every handler untouched. The single most important check is the one the counter test automates: a second request with the cookie must see what the first request stored. Once that holds, the layer is doing its job, and the pages that follow can build the login on top of it.