Sessions
Session lifecycle, token handling, and session management endpoints.
The SessionManagementPlugin provides endpoints for querying, listing, and revoking sessions. Sessions are created automatically during sign-up and sign-in.
Setup
use better_auth::plugins::SessionManagementPlugin;
let auth = BetterAuth::new(config)
.database(database)
.plugin(SessionManagementPlugin::new())
.build()
.await?;Plugin Options
| Option | Type | Default | Description |
|---|---|---|---|
enable_session_listing | bool | true | Allow listing all user sessions |
enable_session_revocation | bool | true | Allow revoking sessions |
require_authentication | bool | true | Require auth for all endpoints |
Authentication Methods
Session tokens can be sent via Bearer header or cookie:
Authorization: Bearer session_abc123...Cookie: better-auth.session-token=session_abc123...The cookie name is configurable via SessionConfig::cookie_name.
Get Current Session
GET /get-session
Authorization: Bearer <token>Response
{
"session": {
"id": "uuid",
"token": "session_abc123...",
"userId": "uuid",
"expiresAt": "2024-01-08T00:00:00Z",
"createdAt": "2024-01-01T00:00:00Z",
"updatedAt": "2024-01-01T00:00:00Z",
"ipAddress": null,
"userAgent": null
},
"user": {
"id": "uuid",
"email": "[email protected]",
...
}
}Returns 401 if the token is missing, invalid, or expired.
Sign Out
POST /sign-out
Authorization: Bearer <token>Revokes the current session. Returns:
{
"success": true
}List Sessions
GET /list-sessions
Authorization: Bearer <token>Returns all active sessions for the authenticated user:
{
"sessions": [
{ "id": "uuid", "token": "session_...", "createdAt": "...", ... },
{ "id": "uuid", "token": "session_...", "createdAt": "...", ... }
]
}Revoke a Specific Session
POST /revoke-session
Authorization: Bearer <token>
Content-Type: application/json{
"token": "session_to_revoke..."
}Returns { "success": true }.
Revoke All Sessions
POST /revoke-sessions
Authorization: Bearer <token>Revokes all sessions for the user, including the current one:
{
"count": 3
}Revoke Other Sessions
POST /revoke-other-sessions
Authorization: Bearer <token>Revokes all sessions except the current one:
{
"count": 2
}Using Sessions in Axum Handlers
With the axum feature, use the CurrentSession extractor to access the authenticated user directly in your handler — no manual token parsing needed:
use better_auth::handlers::CurrentSession;
use better_auth::adapters::MemoryDatabaseAdapter;
use better_auth::AuthUser;
use axum::{Json, response::IntoResponse};
async fn profile(session: CurrentSession<MemoryDatabaseAdapter>) -> impl IntoResponse {
Json(serde_json::json!({
"user_id": session.user.id(),
"session_token": session.session.token(),
}))
}Use OptionalSession for routes that should work for both authenticated and anonymous users. See Axum Integration for full details.
Session Configuration
Session behavior is configured via AuthConfig:
use better_auth::{AuthConfig, SameSite};
use std::time::Duration;
let mut config = AuthConfig::new("secret...");
config.session.expires_in = Duration::hours(24 * 7); // 7 days
config.session.cookie_name = "better-auth.session-token".to_string();
config.session.cookie_secure = true; // HTTPS only
config.session.cookie_http_only = true; // Block JavaScript access
config.session.cookie_same_site = SameSite::Lax; // CSRF protection| Option | Type | Default | Description |
|---|---|---|---|
session.expires_in | Duration | 7 days | Session lifetime |
session.cookie_name | String | better-auth.session-token | Cookie name |
session.cookie_secure | bool | true | HTTPS-only cookie |
session.cookie_http_only | bool | true | Prevent JavaScript access |
session.cookie_same_site | SameSite | Lax | SameSite cookie policy |
See Configuration Options for all session settings.
Session Lifecycle
- Creation: A session is created on successful sign-up, sign-in, or 2FA verification
- Storage: The session token and metadata are stored in the database
- Transmission: The token is returned in the response body and set as a cookie
- Validation: On each authenticated request, the token is verified against the database
- Expiration: Sessions automatically expire after the configured duration
- Revocation: Sessions can be explicitly revoked via the API
Session Fields
| Field | Description |
|---|---|
id | Unique session identifier |
token | Session token (sent as cookie or Bearer token) |
userId | ID of the authenticated user |
expiresAt | Session expiration timestamp |
createdAt | When the session was created |
updatedAt | Last update timestamp |
ipAddress | Client IP address (if available) |
userAgent | Client User-Agent string (if available) |
impersonatedBy | Admin user ID if this is an impersonated session |
activeOrganizationId | Active organization ID (if using Organization plugin) |
Two-Factor Authentication
When 2FA is enabled for a user, the sign-in flow changes:
- User provides email/password — credentials are verified but no session is created
- A pending verification token is returned instead
- User must complete 2FA verification (TOTP, OTP, or backup code)
- Only after successful 2FA verification is a full session created
See Two-Factor Authentication for details.
Session Security
- Token entropy: Tokens are generated using
OsRngwith sufficient entropy - Cookie security: Configure
Secure,HttpOnly, andSameSiteattributes appropriately - IP tracking: Client IP and User-Agent are stored for audit purposes
- Multiple sessions: Users can have multiple active sessions across devices
- Selective revocation: Revoke individual sessions, all sessions, or all except current