Overview
AI Studio uses secure, HTTP-only cookie-based sessions powered by Better Auth. Sessions are created on sign-in and automatically refreshed to keep users logged in.Session Configuration
Sessions are configured inlib/auth.ts:
Total session lifetime in seconds (7 days)
Age threshold for automatic session refresh (1 day)
Session Schema
Sessions are stored in thesession table with the following structure:
Database Indexes
Session Lifecycle
1. Session Creation
Sessions are created when:- User signs in with email/password
- User verifies their email (auto-sign-in)
- Admin impersonates a user
POST /api/auth/sign-in/email
The session token is automatically set as an HTTP-only cookie named
better-auth.session_token.2. Session Validation
On each authenticated request, the session is validated:- Token Check: Session token is extracted from the cookie
- Expiration Check:
expiresAtis compared to current time - User Lookup: Associated user is retrieved from database
- Age Check: If session age >
updateAge, it’s refreshed
3. Session Refresh
Sessions are automatically refreshed when:- Session is valid but older than
updateAge(1 day) - User makes an authenticated request
This “sliding window” approach keeps active users logged in indefinitely, while inactive sessions expire after 7 days.
4. Session Termination
Sessions end when:- User signs out (
POST /api/auth/sign-out) - Session expires (not accessed for 7 days)
- User is banned or deleted
- Admin ends impersonation session
Session Endpoints
Get Current Session
Retrieve the current user session and user information.Headers
Session cookie (automatically sent by browser)
Response
Current session information
Current user information (see Authentication Overview)
Example Request
Example Response
List User Sessions
Retrieve all active sessions for the current user.Headers
Session cookie for authentication
Response
Array of session objects for the current user
Example Request
Example Response
Revoke Session
Revoke a specific session (sign out from a specific device).Headers
Session cookie for authentication
Request Body
ID of the session to revoke
Response
Whether the session was successfully revoked
Example Request
Example Response
Revoke All Sessions
Revoke all sessions except the current one (sign out from all other devices).Headers
Session cookie for authentication
Response
Whether sessions were successfully revoked
Number of sessions that were revoked
Example Request
Example Response
Admin Impersonation Sessions
The Better Auth admin plugin enables admins to impersonate users for support and debugging.Impersonation Configuration
Impersonation Session Fields
User ID of the admin who created the impersonation session
- A new session is created for the target user
- The
impersonatedByfield is set to the admin’s user ID - Session duration is limited to 1 day (regardless of standard session settings)
- Admin can end impersonation to return to their own session
Security Considerations
Impersonation Audit Trail
Impersonation Audit Trail
All impersonation sessions are logged with:
- Admin user ID in
impersonatedByfield - Original IP address and user agent
- Session creation and end times
Limited Duration
Limited Duration
Impersonation sessions expire after 1 day, even if the admin is actively using the account.
Permission Requirements
Permission Requirements
Only users with
isSystemAdmin: true can impersonate other users.Session Security
HTTP-Only Cookies
Sessions use HTTP-only cookies to prevent XSS attacks:Cookie cannot be accessed via JavaScript (prevents XSS)
Cookie only sent over HTTPS in production
Cookie only sent to same-site requests (prevents CSRF)
IP and User Agent Tracking
Each session records:- IP Address: Client IP at session creation
- User Agent: Browser/device information
- Suspicious activity detection
- Session management UI (“Chrome on Windows”, “Safari on iPhone”)
- Geographic anomaly detection
Automatic Cleanup
Expired sessions are automatically cleaned up by Better Auth’s internal cleanup process, which:- Runs periodically in the background
- Deletes sessions where
expiresAt < NOW() - Prevents database bloat from old sessions
Client-Side Usage
React Hook
Use theuseSession hook to access session data in React components:
Session Data Structure
Best Practices
Session Refresh
Let Better Auth handle session refresh automatically. Don’t manually extend sessions.
Cookie Management
Never manually set or modify session cookies. Use Better Auth’s built-in methods.
Multi-Device Support
Allow users to manage sessions across devices using the list/revoke endpoints.
Security Monitoring
Log and monitor session creation from unusual IPs or locations.
Troubleshooting
Session Not Refreshing
Session Not Refreshing
Symptom: User gets logged out after 7 days despite being activeCauses:
- Session cookie is not being sent with requests
updateAgeis not configured correctly- Clock skew between server and database
- Verify
better-auth.session_tokencookie is present in requests - Check session configuration in
lib/auth.ts - Ensure server and database times are synchronized
Session Expires Immediately
Session Expires Immediately
Symptom: User is signed out right after signing inCauses:
expiresInis set too low- Server time is in the future
- Database timestamps are incorrect
- Verify
expiresInis set to 604800 (7 days) - Check server system time
- Inspect
expiresAtvalues in database
Cannot Access Session Cookie
Cannot Access Session Cookie
Session Lost After Deployment
Session Lost After Deployment
Symptom: Users are signed out after deploying new codeCauses:
- Database connection lost during deployment
- Session secret changed
- Cookie domain/path configuration changed
- Use zero-downtime deployments
- Never change
BETTER_AUTH_SECRETin production - Verify cookie configuration in
lib/auth.ts
Related Resources
Authentication Overview
Complete authentication API reference
User Management
Manage users and roles
Better Auth Docs
Official Better Auth documentation
Authentication
Platform authentication architecture