Session Handling
Better Auth provides robust session management with database-backed storage, automatic expiration, and secure token handling.Session Schema
Sessions are stored in the database with the following schema:Session Fields
- id: Unique session identifier
- expiresAt: Session expiration timestamp
- token: Unique session token for authentication
- ipAddress: Client IP address (for security tracking)
- userAgent: Client user agent (browser/device info)
- userId: Reference to the user (cascade delete)
- timestamps: Created/updated/deleted timestamps
Session Middleware
The authentication context middleware extracts session data from requests:Usage
Apply the middleware to protected routes:Authentication Context
The middleware adds authentication data to the Hono context:Accessing Context
Session Creation
Sessions are automatically created by Better Auth during:- User Registration: Creates session after successful sign-up
- User Login: Creates new session after authentication
- Session Refresh: Creates new session when refreshing
Session Storage
Better Auth stores session tokens in HTTP-only cookies by default:Manual Token Handling
For API clients (mobile apps, SPAs), store tokens securely:Session Expiry
Sessions automatically expire based on theexpiresAt timestamp:
Checking Expiration
Session Revocation
Revoke sessions through Better Auth’s API:Session Security
IP Address Tracking
Better Auth tracks IP addresses for security:User Agent Tracking
User agents help identify devices:Auth Routes Handler
Better Auth handles all authentication routes:/api/auth/sign-in/email/api/auth/sign-up/email/api/auth/sign-out/api/auth/session/api/auth/verify-email- And more…
Rate Limiting
Sessions are protected by rate limiting:Best Practices
- Always use middleware: Apply
authContextMiddleware()to protected routes - Check authentication: Verify
userandsessionare not null - Handle expiration: Check session expiry and refresh when needed
- Secure tokens: Use HTTP-only cookies or secure storage
- Track sessions: Monitor IP addresses and user agents for security
- Revoke on logout: Always revoke sessions on user logout
- Cascade deletes: User deletion automatically removes sessions
Next Steps
- User Management - User registration and login
- Authentication Setup - Configure Better Auth
- Better Auth Sessions - Official docs
