Skip to main content

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’s createServerFn() and execute on the server with access to request headers.

fetchSession

Retrieves the current user’s session information from the server.
fetchSession(): Promise<Session | null>

Returns

Session
object | null
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

import { fetchSession } from '@/actions/auth'
import { useEffect, useState } from 'react'

export default function UserProfile() {
  const [session, setSession] = useState<Session | null>(null)
  const [loading, setLoading] = useState(true)
  
  useEffect(() => {
    fetchSession()
      .then(data => setSession(data))
      .finally(() => setLoading(false))
  }, [])
  
  if (loading) {
    return <div>Loading...</div>
  }
  
  if (!session) {
    return (
      <div>
        <p>Not logged in</p>
        <a href="/login">Sign in</a>
      </div>
    )
  }
  
  return (
    <div>
      <h2>Welcome, {session.user.name || session.user.email}</h2>
      {session.user.image && (
        <img 
          src={session.user.image} 
          alt="Profile" 
          width={40} 
          height={40} 
        />
      )}
      <p>Email: {session.user.email}</p>
    </div>
  )
}

How It Works

The fetchSession function:
  1. Extracts the request headers using getWebRequest() from TanStack Start
  2. Passes the headers to your auth library’s getSession() method
  3. Returns the session object or null if no valid session exists
export const fetchSession = createServerFn({ method: 'GET' }).handler(async () => {
  const { headers } = getWebRequest()!

  const session = await auth.api.getSession({
    headers
  })

  return session
})

Authentication Flow

1

Client Request

Client component calls fetchSession() to check authentication status
2

Server Execution

Function executes on the server with access to HTTP request headers
3

Session Validation

Auth library validates session token from cookies/headers
4

Response

Returns session object if valid, or null if unauthenticated

Error Handling

The function returns null 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
Always check for null before accessing session properties to avoid runtime errors.

Security Considerations

Session validation happens entirely on the server. Session tokens are never exposed to client-side JavaScript.
The function uses getWebRequest() to access the original HTTP request headers, ensuring cookies and authentication headers are properly forwarded.
Your auth library handles token validation, expiration checks, and CSRF protection automatically.
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

import { betterAuth } from "better-auth"
import { db } from "./db"

export const auth = betterAuth({
  database: db,
  session: {
    expiresIn: 60 * 60 * 24 * 7, // 7 days
    updateAge: 60 * 60 * 24, // 1 day
  },
  // Additional configuration...
})
Consult your authentication library’s documentation for detailed configuration options and session management features.

Type Definitions

The session type depends on your auth library. To get proper TypeScript support:
import type { Session } from '@/lib/auth'

// Or if using Better Auth
import type { Session } from 'better-auth/types'
For complete authentication types and configuration, refer to your auth library’s documentation and your /home/daytona/workspace/source/src/lib/auth.ts:1 file.