Overview
The authentication server actions provide functions to manage user sessions and authentication state. These actions integrate with your authentication library to securely retrieve session information from server-side requests. All functions are created using TanStack Start’screateServerFn() and execute on the server with access to request headers.
fetchSession
Retrieves the current user’s session information from the server.Returns
Session object containing user information, or null if no active session exists
The exact shape of the
Session object depends on your authentication library configuration. The structure shown above represents a typical session object from Better Auth or similar libraries.Usage
How It Works
ThefetchSession function:
- Extracts the request headers using
getWebRequest()from TanStack Start - Passes the headers to your auth library’s
getSession()method - Returns the session object or
nullif no valid session exists
Authentication Flow
Error Handling
The function returnsnull if:
- No session token is present in the request
- The session token is invalid or expired
- The user has been deleted or deactivated
- Any authentication error occurs
Security Considerations
Server-Side Only
Server-Side Only
Session validation happens entirely on the server. Session tokens are never exposed to client-side JavaScript.
Request Headers
Request Headers
The function uses
getWebRequest() to access the original HTTP request headers, ensuring cookies and authentication headers are properly forwarded.Token Validation
Token Validation
Your auth library handles token validation, expiration checks, and CSRF protection automatically.
Type Safety
Type Safety
The function is strongly typed, providing autocomplete and type checking for session properties.
Best Practices
Cache Session Data
Consider caching the session in client state to avoid repeated server calls on the same page.
Route Protection
Use
fetchSession() in route loaders or beforeLoad hooks to protect entire routes.Optimistic UI
Combine with context or state management for optimistic UI updates after authentication.
Error Boundaries
Wrap authentication-dependent components in error boundaries to handle unexpected failures gracefully.
Integration with Auth Library
This server action integrates with your authentication setup defined in/src/lib/auth. The exact behavior depends on your auth library configuration (e.g., Better Auth, NextAuth, Lucia, etc.).
Configuration
Make sure your auth library is properly configured in/home/daytona/workspace/source/src/lib/auth.ts:1 with:
- Session management enabled
- Cookie-based or header-based authentication
- Proper secret keys and security settings
Example Auth Setup
Type Definitions
The session type depends on your auth library. To get proper TypeScript support:/home/daytona/workspace/source/src/lib/auth.ts:1 file.