Sessions
The Auth class issues sessions on registration and login. It supports two
strategies: JWT (stateless) and database (stored in authSessions).
Session strategies
Section titled “Session strategies”Set the strategy in the auth config:
const auth = createAuth({ db, secret: "my-secret", session: { strategy: "jwt", maxAge: 3600 }, // or "database" providers: [],});- JWT — token carries the user info; no server-side lookup on each request. Revocation relies on expiry. Fastest for most apps.
- Database — session stored in
authSessions. Token is looked up on each request, enabling server-side revocation.
Session lifecycle
Section titled “Session lifecycle”Sessions are created automatically by register() and login():
const { user, session, token } = await auth.register({ email: "ada@example.com", password: "StrongP4ss!",});
// user.email === "ada@example.com"// token is a JWT you send to the clientTo validate a request:
const session = await auth.getSession({ headers: { authorization: "Bearer <token>" },});// SessionData | nullLogout
Section titled “Logout”await auth.logout(token);// For database strategy, the session is deleted.// For JWT strategy, reliance is on token expiry.Token extraction
Section titled “Token extraction”getSession extracts the token from:
Authorization: Bearer <token>header (preferred)auth-token=<token>cookie (fallback)
Best practices
Section titled “Best practices”- Use JWT strategy for most apps (no per-request DB lookup).
- Use database strategy when you need immediate revocation.
- Set
maxAgeto match your app’s session lifetime (default 30 days).
Common mistakes
Section titled “Common mistakes”- Using database strategy on every request for a mobile app (latency).
- Not handling
nullfromgetSession— always check.
Related
Section titled “Related”- Passwords & JWT — the tokens used for sessions.
- OAuth & Providers — social login creates sessions too.
