Session check middleware

Learn how to write a from_fn middleware that requires a session on protected routes and answers 401 when there is none

Handlers can check the session one by one, and the profile handler does exactly that. But when ten routes all need the same check, writing it ten times is ten chances to forget it once. Middleware moves the check out of the handlers and in front of them: one function that runs before a group of routes, reads the session, and either lets the request through or answers 401. This page builds that function and puts it in front of the protected routes only.

Where This Fits

Login writes the user id, handlers read it back, and logout deletes it. The remaining problem is coverage: every route that needs a login must check, and a route that forgets the check serves personal data to strangers. A middleware check fixes the coverage problem by making the check structural instead of habitual. The route does not ask for the check. The check wraps the route, so the route cannot run without it. The public routes stay outside the wrap, and the login route stays outside too, because it is the one route that must work before any session exists.

Think of a building with a guarded floor. Checking identity in every office is the handler approach: it works until one office forgets. Putting a guard at the elevator to that floor is the middleware approach: nobody reaches any office on the floor without passing the guard, and the offices themselves can stop worrying about it.

The Smallest Working Version

The middleware below is a from_fn middleware function. It takes the Session as an extractor, the incoming Request, and a Next value that stands for everything inside the middleware, including the handler. It reads the user id from the session. When one is stored, it runs the next step and returns the response. When none is stored, it returns the Unauthorized error, which becomes status 401 with the shared body. The router puts the middleware on a small protected router with route_layer, and merges that router into the main one, which also carries the session layer.

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 function and a split of the router:

src/lib.rs
pub mod errors;

use argon2::{
    Argon2,
    password_hash::{PasswordHash, PasswordVerifier},
};
use axum::{
    Json, Router,
    extract::{Request, State},
    middleware::{self, Next},
    response::Response,
    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)));

    let protected = Router::new()
        .route("/me", get(me))
        .route_layer(middleware::from_fn(require_session));

    Router::new()
        .route("/login", post(login))
        .route("/logout", post(logout))
        .route("/public", get(public))
        .merge(protected)
        .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<axum::http::StatusCode> {
    session
        .flush()
        .await
        .map_err(|_| AppError::InternalError)?;
    Ok(axum::http::StatusCode::OK)
}

async fn require_session(
    session: Session,
    request: Request,
    next: Next,
) -> Result<Response, AppError> {
    match session.get::<i32>("user_id").await {
        Ok(Some(_)) => Ok(next.run(request).await),
        Ok(None) => Err(AppError::Unauthorized),
        Err(_) => Err(AppError::InternalError),
    }
}

Start the server with cargo run and try the protected route three ways: with no cookie, after logging in, and after logging out:

curl http://127.0.0.1:3000/me
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 -b cookies.txt -X POST http://127.0.0.1:3000/logout
curl -b cookies.txt http://127.0.0.1:3000/me

The output is:

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

The first request has no cookie, so the middleware answers 401 and the handler never runs. The login succeeds and saves the cookie. The third request carries the cookie, so the middleware lets it through and the handler returns the user. The fourth logs out, and the fifth sends the old cookie to a route that now finds no session, so the middleware answers 401 again. The same 401 appears in the first and last requests for different reasons: the first never had a session, and the last had one that was flushed. The middleware does not care which. It only checks what is there now.

Working Setup:

If the protected route answers 401 without a cookie and 200 with one, while the login and public routes keep working without any cookie, the middleware is in the right place. The check guards the protected routes and nothing else.

How the Middleware Function Works

The from_fn shape has strict rules, and this function follows all of them. It is an async function. It takes extractors that read from the request parts, here the Session, and it takes exactly one extractor that reads the whole request, the Request itself. It takes Next as its last argument. It returns something that implements IntoResponse, and a Result<Response, AppError> qualifies, because both Response and AppError can be turned into a response.

async fn require_session(
    session: Session,
    request: Request,
    next: Next,
) -> Result<Response, AppError> {
    match session.get::<i32>("user_id").await {
        Ok(Some(_)) => Ok(next.run(request).await),
        Ok(None) => Err(AppError::Unauthorized),
        Err(_) => Err(AppError::InternalError),
    }
}

The three arms of the match are the same three outcomes the profile handler's read has, and they mean the same things. Ok(Some(_)) means a user id is stored, and the underscore says the value itself is not needed here: the middleware only needs to know that one exists. next.run(request).await passes the request inward to the handler and waits for the response, which the middleware returns unchanged. Ok(None) means the session is empty, and the middleware returns Unauthorized without ever calling next, so the handler never runs. Err(_) means the read failed, which is a bug in the program, so the middleware returns InternalError and status 500.

The return type is what makes the ? operator unnecessary here and the Err returns natural. A from_fn middleware that returns a Result can return errors directly, and Axum turns the error into a response through its IntoResponse implementation. The AppError type already implements that, so the middleware needs no response-building code of its own.

The middleware reads the session, it does not load the user:

require_session checks that a user id is stored. It does not load the user from the database, and it does not check that the id still has a row. That second check stays in the handler, where the user data is actually needed. The middleware answers the question of whether anyone is logged in. The handler answers the question of who that is.

How route_layer Scopes the Check

route_layer applies middleware to the routes that were already added to that router, and only to those routes. In this program the protected router holds one route when route_layer is called, so the middleware wraps /me and nothing else. The main router holds the login, logout, and public routes, and the protected router is merged into it afterwards. merge combines two routers into one, keeping each route's own middleware.

The order of the calls is the scope. Routes added to the protected router after the route_layer call are not wrapped, because the layer was already applied. Routes on the main router are never wrapped by the protected router's route_layer, because the call belongs to the protected router, not to the main one. That is what keeps the login route public: it lives on the main router, outside the wrap, so a visitor with no session can still log in.

The session layer, by contrast, is attached with .layer to the whole merged router, so it wraps every route. That is correct, because every route may need a session: login writes one, logout flushes one, the profile reads one, and the public route simply ignores the empty one it gets. The session layer must also run before the check middleware, because the check reads the Session from the request, and only the session layer puts it there. The ordering works out because of how layers stack: the .layer call added last wraps everything added before it, so the session layer is the outermost layer and runs first on every request.

The Request Flow Through the Layers

The path of a request to the protected route, with both layers in place, looks like this:

Browser sends request with cookie id=abc123
        |
        v
Session layer loads the session and puts it in the request
        |
        v
require_session reads user_id from the session
        |
        v
user_id present: next.run passes the request to the handler
user_id missing: middleware answers 401, handler never runs
        |
        v
Handler loads the user and returns JSON
        |
        v
Session layer saves the session if it changed
        |
        v
Response goes back to the browser

The two layers do different jobs at different depths. The session layer is outermost: it prepares the session for everything inside it. The check middleware sits between the session layer and the handler: it decides whether the request may proceed. The handler is innermost: it does the work, trusting that the request was already checked. A request that fails the check never reaches the handler, and the handler never has to repeat the check.

A Richer Example - Several Protected Routes

One protected route shows the shape. Several protected routes show why the shape is worth having. This example adds a settings route and a notes route to the protected router. Both read the user id from the session, and neither repeats the check, because the route_layer call wraps all three routes at once:

src/lib.rs
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)));

    let protected = Router::new()
        .route("/me", get(me))
        .route("/settings", get(settings))
        .route("/notes", get(notes))
        .route_layer(middleware::from_fn(require_session));

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

async fn settings(
    State(pool): State<PgPool>,
    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 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(serde_json::json!({
        "id": user.id,
        "name": user.name,
        "email": user.email,
    })))
}

async fn notes(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),
    };
    Ok(Json(serde_json::json!({
        "user_id": user_id,
        "notes": [],
    })))
}

All three routes are added to the protected router before the route_layer call, so all three are wrapped. A visitor with no cookie gets 401 from /me, from /settings, and from /notes, and the check was written once. Adding a fourth protected route means adding one line to this router, before the route_layer call, and the check comes with it. The notes handler shows that a protected handler still reads the user id itself when it needs the value: the middleware proved that one is stored, and the handler uses it. The settings handler shows the same read followed by a database lookup, just like the profile handler.

Answering With a Redirect Instead of a 401

A 401 is the right answer for an API client, which reads the status code and handles it in code. A browser visiting a page is different: a person who opens a protected page without logging in expects to land on the login page, not on a JSON error. A middleware variant that redirects does that, by answering 303 with a Location header instead of a 401:

src/lib.rs
async fn require_session_or_redirect(
    session: Session,
    request: Request,
    next: Next,
) -> Response {
    match session.get::<i32>("user_id").await {
        Ok(Some(_)) => next.run(request).await,
        _ => Response::builder()
            .status(StatusCode::SEE_OTHER)
            .header(header::LOCATION, "/login")
            .body(axum::body::Body::empty())
            .unwrap(),
    }
}

StatusCode::SEE_OTHER is status 303, which tells the browser to make a GET request to the address in the Location header. The response is built with Response::builder, which sets the status, adds the header with the header::LOCATION constant from axum::http::header, and finishes with an empty body. The return type here is a plain Response rather than a Result, because this variant has no error case of its own: any failure to read the session redirects just like a missing value, which is the safe choice for a browser flow, where sending the visitor to log in again is never the wrong move.

Which variant to use depends on who calls the route. An API that serves JSON answers 401, because its clients are programs. A site that serves pages redirects, because its clients are people with browsers. An application with both kinds of routes can use both variants, one on the API router and one on the page router, and the choice is made per router, not per handler.

Testing It

Three tests cover this page. The first checks that the protected route answers 401 without a cookie. The second checks that the login route stays public, by logging in successfully with no cookie at all. The third checks the scope rule directly: a route added to the protected router after the route_layer call is not wrapped, so it answers 200 without a session. 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},
    middleware::Next,
    response::Response,
    routing::get,
};
use axum_project::{app, errors::AppError};
use serde_json::json;
use sqlx::PgPool;
use tower::ServiceExt;
use tower_sessions::{MemoryStore, Session, SessionManagerLayer};

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

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

#[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\"}");
}

#[tokio::test]
async fn login_stays_public_without_a_cookie() {
    let response = app(pool().await)
        .oneshot(
            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(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::OK);
}

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

async fn require_session_local(
    session: Session,
    request: axum::extract::Request,
    next: Next,
) -> Result<Response, AppError> {
    match session.get::<i32>("user_id").await {
        Ok(Some(_)) => Ok(next.run(request).await),
        _ => Err(AppError::Unauthorized),
    }
}

#[tokio::test]
async fn route_added_after_route_layer_is_not_protected() {
    let app = Router::new()
        .route("/me", get(needs_session))
        .route_layer(axum::middleware::from_fn(require_session_local))
        .route("/late", get(needs_session))
        .layer(SessionManagerLayer::new(MemoryStore::default()).with_secure(false));
    let guarded = app
        .clone()
        .oneshot(
            Request::builder()
                .uri("/me")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(guarded.status(), StatusCode::UNAUTHORIZED);
    let late = app
        .oneshot(
            Request::builder()
                .uri("/late")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(late.status(), StatusCode::OK);
}

The first test calls /me with no cookie and expects the 401 with the shared body, which proves the middleware runs before the handler. The second test posts to /login with no cookie and expects 200, which proves the login route escaped the wrap. The third test builds its own router with the same middleware shape: /me is added before route_layer and answers 401 without a cookie, while /late is added after route_layer and answers 200 without a cookie, which proves the scope rule in one test. The local middleware in the test is a copy of the real one, kept short by mapping every failure to Unauthorized, because the test only needs the pass and fail behaviour, not the 500 arm. Run all three with cargo test.

What the tests prove:

The three tests draw the boundary of the check: the protected route refuses, the login route allows, and the scope ends exactly where route_layer was called. A middleware that passes all three guards what it should and nothing it should not.

Common Beginner Mistakes

Guarding the login route too

// Wrong - the check wraps every route, including login, so nobody can log in
let app = Router::new()
    .route("/login", post(login))
    .route("/me", get(me))
    .layer(middleware::from_fn(require_session))
    .layer(session_layer)
    .with_state(pool);

This router applies the check to the whole router with .layer, so it wraps /login as well as /me. A visitor with no session asks to log in, the middleware finds no user id, and answers 401 before the login handler ever runs. There is no way to get a session, because getting one requires passing a check that requires one. The fix is the split router at the top of this page: the check goes on a protected router with route_layer, and the login route stays on the main router outside it. Whenever login answers 401 for a correct password, the first thing to check is whether the login route accidentally ended up inside the guard.

A guarded login is a locked door with the key inside:

Protecting the login route creates a loop with no exit: the session is required to log in, and logging in is the only way to get a session. The symptom is a 401 on every login attempt, including correct ones. Keep login, and any route that creates a session, outside every session check.

Putting the check outside the session layer

// Wrong - the check runs before the session layer loads the session
let app = Router::new()
    .route("/me", get(me))
    .layer(session_layer)
    .layer(middleware::from_fn(require_session));

Layers added later wrap everything added before them, so the check added last is outermost and runs first. It looks for a Session in the request, finds nothing, because the session layer inside it has not run yet, and the extractor rejects with a 500. The fix is the order in the program at the top of this page: the session layer is added last, so it is outermost and runs first, and the check middleware sits inside it, where the session is already loaded. The rule is short: the session layer must wrap the check, never the other way around.

Adding a route after route_layer

// Wrong - /notes is added after route_layer, so it is not wrapped
let protected = Router::new()
    .route("/me", get(me))
    .route_layer(middleware::from_fn(require_session))
    .route("/notes", get(notes));

/me is wrapped and /notes is not, because route_layer only wraps the routes that existed when it was called. /notes serves personal data to anyone who asks, with no check at all, and the program compiles and runs without complaint. The fix is to add every protected route before the route_layer call, as the richer example above does. When a new protected route is added later, it must go above that line, not below it. A quick test with no cookie on every protected route catches this mistake the moment it is made.

An unwrapped route fails open, not closed:

A route that misses the route_layer call does not answer 401. It answers with the data, because nothing stands between the request and the handler. That is the worst direction for a security mistake: the program looks correct, the protected routes work, and the unprotected one quietly serves personal data to strangers. Test every protected route without a cookie after any router change.

Checking in the handler as well as the middleware

A handler behind the check that repeats the same session read is not wrong, exactly, but it is wasteful in the wrong way: it duplicates the check, and the two copies can drift apart when one is changed and the other is not. The handler should use the user id, as the profile handler does when it loads the user, and trust the middleware for the refusal. If a handler needs a different rule from the group, such as an extra condition of its own, that rule belongs in the handler, and it should be written as the extra condition it is, not as a second copy of the group check.

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 logout that ends it, and the middleware that guards the protected routes.

src/lib.rs
pub mod errors;

use argon2::{
    Argon2,
    password_hash::{PasswordHash, PasswordVerifier},
};
use axum::{
    Json, Router,
    extract::{Request, State},
    middleware::{self, Next},
    response::Response,
    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)));

    let protected = Router::new()
        .route("/me", get(me))
        .route("/settings", get(settings))
        .route("/notes", get(notes))
        .route_layer(middleware::from_fn(require_session));

    Router::new()
        .route("/login", post(login))
        .route("/logout", post(logout))
        .route("/public", get(public))
        .merge(protected)
        .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 settings(
    State(pool): State<PgPool>,
    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 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(serde_json::json!({
        "id": user.id,
        "name": user.name,
        "email": user.email,
    })))
}

async fn notes(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),
    };
    Ok(Json(serde_json::json!({
        "user_id": user_id,
        "notes": [],
    })))
}

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

async fn require_session(
    session: Session,
    request: Request,
    next: Next,
) -> Result<Response, AppError> {
    match session.get::<i32>("user_id").await {
        Ok(Some(_)) => Ok(next.run(request).await),
        Ok(None) => Err(AppError::Unauthorized),
        Err(_) => Err(AppError::InternalError),
    }
}

Run it with cargo run and test it with cargo test. Ask for /me without a cookie and watch the 401 arrive before the handler runs. Log in, ask again, and watch the user come back. That pair of answers is the middleware doing its job: one check, written once, standing in front of every route it wraps.

Summary

The check moved from the handlers to the structure around them, and that move is the whole lesson. A check written in a handler protects one route until someone forgets to write it in the next one. A check wrapped around a router protects every route in that router, including the ones added next month, as long as they are added above the route_layer line. The decision that follows is about where the boundary sits: one route with its own rule keeps the check in the handler, where the rule is visible next to the code it guards. A group of routes with one rule keeps the check in middleware, where it cannot be forgotten. And the boundary itself needs the same care as the check: the session layer must wrap the middleware, the login route must stay outside it, and every protected route must be added before the wrap. Get those three placements right, and the guard holds without any handler thinking about it.