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

1. Configure BetterAuth

// 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

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

// 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

// 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