HTTP
Session
Remember a visitor between requests, on the server.
HTTP forgets everything between requests. A session is the server's memory of one visitor: their cart, the fact they are signed in. The browser only holds a session id in a cookie; the data stays on the server, so the visitor cannot read or change it.
app.http(adapter) { useSession { cookieName = "app.sid"; ttl = Duration.ofHours(8); secure = true; sameSite = "Lax" } }
@Controller("/cart")
class CartController {
@Post("/add") fun add(@Query item: String, session: Session): List<String> {
val items = (session["items"] as? List<*> ?: emptyList<Any>()) + item
session["items"] = items // saved automatically when the response is sent
return items.map { it.toString() }
}
@Post("/logout") fun logout(session: Session) { session.destroy() }
}Take a Session parameter in any handler. Read with session["key"], write with session["key"] = value, end with session.destroy().
- A session is created (and a cookie set) only when something is stored, unless
saveUninitialized = true.session.isNewtells a first visit. - Values must be JSON-compatible (strings, numbers, booleans, lists, maps), so every store can hold them. Store ids, not whole entities.
ttlis how long an idle session lives.
Stores: where the data lives
| Store | Behaviour |
|---|---|
| memory (the default) | one instance only; lost on restart. Fine for development |
| Redis | useSession { store = RedisSessionStore("redis-host") } from the session-redis package: any instance can serve any request, and sessions survive restarts |
With more than one instance behind a load balancer you must use a shared store (or "sticky" routing).
Signing in with a session
After checking the password: session["userId"] = user.id. Later requests read it. On login, create a fresh session (destroy the old one) to prevent session fixation. Cookie-based sessions need CSRF protection, and should be secure and HttpOnly (the defaults for the id cookie apart from secure, which you set).
Session or token?
Sessions: easy logout, small cookie, data stays private, but needs a store. Tokens (JWT): no store, work across services, but harder to revoke. See Authentication.