Overview
The Inmobiliaria API uses session-based authentication with HTTP-only cookies. Sessions are automatically created upon successful authentication (sign-up, sign-in, or OAuth) and validated on subsequent requests.Session Configuration
Sessions are configured insrc/auth/index.ts:
Session expiration time: 30 days (2,592,000 seconds)
Session refresh threshold: 7 days (604,800 seconds). If a session is older than this, it will be extended on the next request.
How Sessions Work
1. Session Creation
When a user successfully authenticates (via email/password or OAuth), Better Auth:- Generates a unique session ID and token
- Stores session data in the
sessionstable - Sets an HTTP-only cookie with the session token
- Returns user and session information
Session Cookie
Cookie Attributes
2. Session Storage
Session data is stored in the PostgreSQL database:Session Table Schema
Unique session identifier
Encrypted session token (matches cookie value)
When the session expires (30 days from creation)
Reference to the authenticated user
IP address where session was created (optional)
Browser user agent (optional)
Session creation timestamp
Last session update timestamp
3. Session Validation
On each authenticated request, the API validates the session:- Extracts session token from cookie
- Queries the
sessionstable - Verifies token signature and expiration
- Loads associated user data
- Attaches user to request object
Get Current Session
Retrieve the current user’s session information:GET /api/session
The
-b cookies.txt flag includes the session cookie in the request.Response
Implementation
The session endpoint is defined insrc/index.ts:
Session Lifecycle
Session Extension
Sessions are automatically extended if:- The session age is older than
updateAge(7 days) - The session hasn’t expired yet
- The user makes an authenticated request
expiresAtis updated to 30 days from nowupdatedAttimestamp is refreshed- Session cookie
Max-Ageis reset
Session Expiration
Sessions expire after 30 days of inactivity. Expired sessions:- Are automatically cleaned up from the database
- Return
401 Unauthorizedon validation - Require the user to sign in again
Manual Session Termination
Users can manually end their session by signing out:POST /api/auth/sign-out
- Deletes the session from the database
- Clears the session cookie
- Returns success response
Using Sessions in Requests
All authenticated endpoints require including the session cookie:CORS Configuration
For cookies to work with cross-origin requests, CORS must be properly configured:Trusted Origins
Only requests from trusted origins can create and use sessions.
Client-Side Session Management
React Hook Example
Usage
Security Best Practices
HTTP-Only Cookies
HTTP-Only Cookies
Secure Flag
Secure Flag
In production, cookies require HTTPS:
SameSite Protection
SameSite Protection
SameSite=None allows cross-origin requests but requires Secure=true:Session Rotation
Session Rotation
Sessions are automatically refreshed every 7 days, limiting the window for session hijacking.
IP & User Agent Tracking
IP & User Agent Tracking
Sessions store IP address and user agent for anomaly detection:
Troubleshooting
Session not persisting
Session not persisting
Symptoms: User is logged out on page refreshCauses & Solutions:
- Missing
credentials: 'include'in fetch requests - CORS not configured with
credentials: true - Frontend URL not in
trustedOrigins - Browser blocking third-party cookies (use same domain or educate users)
SameSite=NonerequiresSecure=true(use HTTPS)
401 Unauthorized
401 Unauthorized
CORS errors
CORS errors
Symptoms: Browser blocks requests with CORS errorCauses & Solutions:
- Frontend URL not in CORS
originarray - Missing
credentials: truein CORS config - Preflight request failing - ensure OPTIONS requests allowed
- Mismatched protocols (http vs https)
Next Steps
Authentication Middleware
Learn how to protect routes with session validation
Email/Password Auth
Implement email and password authentication
OAuth (Google)
Add Google OAuth authentication
User Profile
Access user information from sessions