StarterApp Docs
CodebaseFoundations

BetterAuth

Type-safe authentication with edge compatibility and real-time session management

BetterAuth provides type-safe authentication for modern applications. The library runs on edge networks, integrates with any database, and maintains full TypeScript support throughout the authentication flow.

Pro Tip

BetterAuth combines type safety, edge runtime compatibility, and real-time session management to provide a comprehensive authentication solution for modern web applications.

TypeScript-First Design

BetterAuth generates complete type definitions for authentication:

Type-safe session handling
const session = await auth.getSession();
if (session) {
  // TypeScript knows exact shape
  console.log(session.user.id);
  console.log(session.user.email);
  console.log(session.user.name);
}

Type safety extends through the entire authentication flow. Session types, user objects, and auth methods all have precise definitions. AI assistants leverage these types to generate correct authentication code.

Edge Runtime Compatibility

The library executes on modern JavaScript runtimes:

  • Vercel Edge Functions
  • Cloudflare Workers
  • Deno Deploy
  • Node.js

Authentication runs close to users globally. No specific platform requirements. The same code deploys anywhere JavaScript runs.

Security Architecture

BetterAuth implements authentication security standards:

CSRF tokens prevent cross-site request forgery. HttpOnly cookies protect session tokens from JavaScript access. Automatic token rotation limits compromise windows. Rate limiting blocks brute force attempts.

These protections activate by default. Configuration remains optional for specific requirements.

OAuth Provider Integration

Social authentication requires minimal configuration:

OAuth provider configuration
export const auth = createAuth({
  providers: {
    google: {
      clientId: env.GOOGLE_CLIENT_ID,
      clientSecret: env.GOOGLE_CLIENT_SECRET,
    },
    github: {
      clientId: env.GITHUB_CLIENT_ID,
      clientSecret: env.GITHUB_CLIENT_SECRET,
    },
  },
});

OAuth complexity stays hidden. State validation and redirect handling happen automatically. Providers integrate through standardized configuration.

Real-Time Session Management

BetterAuth combines with Convex for live authentication state:

Real-time session with Convex
// Store session in Convex
await ctx.db.insert("sessions", {
  userId: session.userId,
  token: session.token,
  expiresAt: session.expiresAt,
});

// Query updates when auth changes
export const getCurrentUser = query({
  handler: async (ctx) => {
    const token = await getAuthToken();
    if (!token) return null;

    const session = await ctx.db
      .query("sessions")
      .withIndex("byToken", (q) => q.eq("token", token))
      .first();

    return session?.user;
  },
});

Authentication state synchronizes across all connected clients. Sign-in on one device reflects immediately everywhere. Permission changes propagate instantly.

AI-Assisted Development

BetterAuth patterns enable accurate AI code generation through consistent authentication flows and complete type coverage. Protected route patterns repeat predictably:

Protected route pattern
export const dynamic = 'force-dynamic';

export default async function ProtectedPage() {
  const user = await getCurrentUser();
  if (!user) redirect('/sign-in');

  // Page content
}

AI assistants understand these patterns and generate matching implementations. Type definitions guide code generation preventing invalid auth logic. Standard patterns apply everywhere making AI suggestions consistent.

Session Performance

Authentication avoids common performance bottlenecks:

  • Sessions validate without database queries
  • Edge execution reduces latency
  • WebSocket connections enable instant updates
  • Optimistic UI updates improve perceived speed

The architecture prioritizes response time while maintaining security.

Database Flexibility

BetterAuth works with any database through adapters:

Database adapter configuration
// Convex adapter
const auth = createAuth({
  database: convexAdapter(ctx),
});

// Postgres, MySQL, SQLite also supported

Existing databases integrate without schema changes. Authentication data coexists with application data.

Additional Resources