> ## Documentation Index
> Fetch the complete documentation index at: https://docs.builderbox.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Session Management

> Learn how to manage user sessions in your application

## Server-Side Setup in `apps/server/src/lib/auth.ts`

### 1. Configure BetterAuth

```typescript theme={null}
// apps/server/src/lib/auth.ts
import { betterAuth } from "better-auth";
import { prismaAdapter } from "better-auth/adapters/prisma";

export const auth = betterAuth({
  database: prismaAdapter(prisma, {
    provider: "postgresql",
  }),

  advanced: {
    crossSubDomainCookies: {
      enabled: true,
    },
  },
});
```

### 2. Session Schema

```prisma theme={null}
model Session {
  id        String   @id @map("_id")
  expiresAt DateTime
  token     String   @unique
  createdAt DateTime
  updatedAt DateTime
  ipAddress String?
  userAgent String?
  userId    String
  user      User     @relation(fields: [userId], references: [id], onDelete: Cascade)
}
```

## Client-Side Implementation

### 1. Auth Client Setup

```typescript theme={null}
// apps/web/src/lib/auth-client.ts
import { createAuthClient } from "better-auth/react";

export const authClient = createAuthClient({
  baseURL: process.env.NEXT_PUBLIC_SERVER_URL!,
});
```

### 2. get session

```typescript theme={null}
// apps/web/src/hooks/use-session.ts
import { authClient } from "@/lib/client"
 
const { data: session } = authClient.useSession()
```

## Security Features

1. **Session Storage**
   * Secure cookie storage
   * HTTP-only cookies
   * SameSite policy
   * CSRF protection

2. **Session Validation**
   * Token verification
   * Expiration checks
   * IP validation
   * User agent validation

3. **Session Refresh**
   * Automatic refresh
   * Sliding expiration
   * Refresh token rotation
   * Concurrent session handling

## Best Practices

1. **Session Security**
   * Use secure cookies
   * Implement CSRF protection
   * Validate session data
   * Monitor session activity

2. **Error Handling**
   * Handle expired sessions
   * Manage invalid tokens
   * Clear invalid sessions
   * Log session errors

3. **User Experience**
   * Smooth session refresh
   * Clear session states
   * Handle session loss
   * Provide feedback

## Common Issues & Solutions

1. **Session Expiry**
   * Implement refresh logic
   * Handle expired sessions
   * Clear invalid sessions
   * Update session data

2. **Cross-Domain Issues**
   * Configure CORS
   * Set cookie domains
   * Handle subdomains
   * Validate origins

3. **Concurrent Sessions**
   * Manage multiple sessions
   * Handle conflicts
   * Update session data
   * Clear old sessions

## Next Steps

* [Set up Email & Password authentication](/auth/email-pass)
* [Set up Social authentication](/auth/socials)
* [Configure protected routes](/auth/protected-routes)
