Skip to content

secondsky/claude-skills / plugins/better-auth/skills/better-auth

better-auth

Verified

Skill for integrating Better Auth - comprehensive TypeScript authentication framework for Cloudflare D1, Next.js, Nuxt, and 15+ frameworks. Use when adding auth, encountering D1 adapter errors, or implementing OAuth/2FA/RBAC features.

FileKindSize
SKILL.mdskill md29.2 KB
assets/auth-flow-diagram.mdmarkdown24.0 KB
references/advanced-features.mdmarkdown14.7 KB
references/cloudflare-worker-drizzle.tsscript12.7 KB
references/cloudflare-worker-kysely.tsscript9.7 KB
references/configuration-guide.mdmarkdown10.7 KB
references/database-schema.tsscript10.8 KB
references/databases/mongodb.mdmarkdown5.3 KB
references/databases/mysql.mdmarkdown6.8 KB
references/databases/postgresql.mdmarkdown8.4 KB
references/error-catalog.mdmarkdown12.9 KB
references/framework-comparison.mdmarkdown8.2 KB
references/frameworks/api-frameworks.mdmarkdown9.2 KB
references/frameworks/expo-mobile.mdmarkdown8.7 KB
references/frameworks/nextjs.mdmarkdown5.4 KB
references/frameworks/nuxt.mdmarkdown6.0 KB
references/frameworks/remix.mdmarkdown6.1 KB
references/frameworks/sveltekit.mdmarkdown6.3 KB
references/integrations/electron.mdmarkdown8.2 KB
references/migration-guide-1.4.0.mdmarkdown23.2 KB
references/migration-guide-1.5.0.mdmarkdown6.3 KB
references/nextjs/README.mdmarkdown1.1 KB
references/nextjs/postgres-example.tsscript4.0 KB
references/plugins/api-tokens.mdmarkdown10.0 KB
references/plugins/authentication.mdmarkdown9.2 KB
references/plugins/enterprise.mdmarkdown9.1 KB
references/plugins/payments.mdmarkdown8.0 KB
references/plugins/sso.mdmarkdown9.4 KB
references/plugins/test-utils.mdmarkdown5.5 KB
references/react-client-hooks.tsxother12.8 KB
references/setup-guide.mdmarkdown8.9 KB
references/v1.4-features.mdmarkdown8.2 KB
references/v1.5-features.mdmarkdown11.0 KB
references/v1.6-features.mdmarkdown6.1 KB
scripts/generate-secret.shexecutablescript2.0 KB
scripts/setup-d1-drizzle.shexecutablescript10.2 KB
scripts/test-auth-health.shexecutablescript2.1 KB
scripts/validate-config.tsscript4.3 KB

references/configuration-guide.md

View on GitHub
# Better-Auth Configuration Guide

**Last Updated**: 2026-04-08
**Package**: `better-auth@1.6.0`
**Requirements**: ESM-only (v1.4.0+)

---

## Overview

This guide provides complete configuration examples for better-auth v1.4.0+ with Cloudflare D1, Drizzle ORM, and Hono.

**CRITICAL**: better-auth v1.4.0+ is **ESM-only**. CommonJS is no longer supported.

---

## ESM Requirements

### package.json

```json
{
  "type": "module",
  "scripts": {
    "dev": "wrangler dev",
    "deploy": "wrangler deploy"
  },
  "dependencies": {
    "better-auth": "^1.6.0",
    "drizzle-orm": "^0.45.2",
    "hono": "^4.12.12"
  }
}
```

### Import Syntax

```typescript
// ✅ CORRECT (ESM)
import { betterAuth } from "better-auth";
import { drizzleAdapter } from "better-auth/adapters/drizzle";

// ❌ WRONG (CommonJS - no longer works)
const { betterAuth } = require('better-auth');
```

---

## Minimal Configuration

For quick setup with email/password authentication:

```typescript
import { betterAuth } from "better-auth";
import { drizzleAdapter } from "better-auth/adapters/drizzle";
import { drizzle } from "drizzle-orm/d1";
import * as schema from "./db/schema";

export function createAuth(env: {
  DB: D1Database;
  BETTER_AUTH_SECRET: string;
  BETTER_AUTH_URL: string;
}) {
  const db = drizzle(env.DB, { schema });

  return betterAuth({
    baseURL: env.BETTER_AUTH_URL,
    secret: env.BETTER_AUTH_SECRET,
    database: drizzleAdapter(db, { provider: "sqlite" }),
  });
}
```

---

## Production Configuration

Complete setup with email/password and social providers:

```typescript
import { betterAuth } from "better-auth";
import { drizzleAdapter } from "better-auth/adapters/drizzle";
import { drizzle } from "drizzle-orm/d1";
import * as schema from "./db/schema";

export function createAuth(env: Env) {
  const db = drizzle(env.DB, { schema });

  return betterAuth({
    baseURL: env.BETTER_AUTH_URL,
    secret: env.BETTER_AUTH_SECRET,

    database: drizzleAdapter(db, { provider: "sqlite" }),

    emailAndPassword: {
      enabled: true,
      requireEmailVerification: true,
      sendVerificationEmail: async ({ user, url, token, ctx }) => {
        // v1.4.0+: callback signature changed (request → ctx)
        await sendEmail({
          to: user.email,
          subject: "Verify your email",
          html: `<a href="${url}">Verify Email</a>`,
        });
      },
    },

    socialProviders: {
      google: {
        clientId: env.GOOGLE_CLIENT_ID,
        clientSecret: env.GOOGLE_CLIENT_SECRET,
        scope: ["openid", "email", "profile"],
      },
      github: {
        clientId: env.GITHUB_CLIENT_ID,
        clientSecret: env.GITHUB_CLIENT_SECRET,
        scope: ["user:email", "read:user"],
      },
      // v1.4.3+ New: Vercel provider
      vercel: {
        clientId: env.VERCEL_CLIENT_ID,
        clientSecret: env.VERCEL_CLIENT_SECRET,
      },
    },

    session: {
      expiresIn: 60 * 60 * 24 * 7, // 7 days
      updateAge: 60 * 60 * 24, // Update every 24 hours
      // v1.4.0+: JWE encryption by default (cookie caching)
    },

    // v1.4.0+ New: Trusted proxy headers support
    trustedOrigins: ["https://yourdomain.com"],
  });
}
```

---

## wrangler.toml Configuration

```toml
name = "my-app"
compatibility_date = "2024-11-01"
compatibility_flags = ["nodejs_compat"]

[[d1_databases]]
binding = "DB"
database_name = "my-app-db"
database_id = "your-database-id"

[vars]
BETTER_AUTH_URL = "https://yourdomain.com"

# Set secrets via: wrangler secret put SECRET_NAME
# Required secrets:
# - BETTER_AUTH_SECRET (generate: openssl rand -base64 32)
# - GOOGLE_CLIENT_ID
# - GOOGLE_CLIENT_SECRET
# - GITHUB_CLIENT_ID
# - GITHUB_CLIENT_SECRET
```

---

## Environment Variables

### Local Development (.dev.vars)

```bash
# DO NOT COMMIT THIS FILE
BETTER_AUTH_URL=http://localhost:8787
BETTER_AUTH_SECRET=your-secret-here-generate-with-openssl
GOOGLE_CLIENT_ID=your-google-client-id
GOOGLE_CLIENT_SECRET=your-google-secret
GITHUB_CLIENT_ID=your-github-client-id
GITHUB_CLIENT_SECRET=your-github-secret
```

### Production Secrets

```bash
# Set via Wrangler CLI (not in wrangler.toml)
wrangler secret put BETTER_AUTH_SECRET
wrangler secret put GOOGLE_CLIENT_ID
wrangler secret put GOOGLE_CLIENT_SECRET
wrangler secret put GITHUB_CLIENT_ID
wrangler secret put GITHUB_CLIENT_SECRET
```

---

## Advanced Configuration Options

### CORS Configuration

For cross-origin requests (e.g., frontend on different domain):

```typescript
import { Hono } from "hono";
import { cors } from "hono/cors";

const app = new Hono<{ Bindings: Env }>();

app.use("/api/auth/*", cors({
  origin: ["https://yourdomain.com", "http://localhost:3000"],
  credentials: true, // CRITICAL: Required for sessions
  allowMethods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
}));

app.all("/api/auth/*", async (c) => {
  const auth = createAuth(c.env);
  return auth.handler(c.req.raw);
});
```

### Session Configuration (v1.4.0+)

```typescript
session: {
  expiresIn: 60 * 60 * 24 * 7, // 7 days
  updateAge: 60 * 60 * 24, // Update every 24 hours
  // v1.6+: `freshAge` window is measured from session `createdAt`, not `updatedAt`.
  // Regular access no longer keeps a session "fresh" indefinitely — sensitive ops
  // (payments, password change) will force re-auth sooner. Set `freshAge: 0` to disable.
  freshAge: 60 * 5, // 5 minutes from session CREATION (v1.6 semantics)

  // v1.4.0+ New: Cookie caching with JWE encryption (stateless sessions)
  cookieCache: {
    enabled: true,
    maxAge: 60 * 5, // 5 minutes
    strategy: "jwe", // "jwe", "jwt", or "compact" for stateless sessions
  },
  // Note: For stateless sessions, omit database session storage and use cookieCache strategy
  // v1.6+: cookieCache `maxAge` is clamped to session `expiresIn`.
}
```

### Rate Limiting Configuration

```typescript
import { betterAuth } from "better-auth";
import { rateLimit } from "better-auth/plugins";

export const auth = betterAuth({
  // ... other config
  plugins: [
    rateLimit({
      window: 60 * 1000, // 1 minute
      max: 10, // 10 requests per minute
    }),
  ],
});
```

### API Key Plugin (v1.5+ — moved to separate package)

The `apiKey` plugin was extracted from `better-auth/plugins` into a dedicated
package in v1.5. Install it separately:

```bash
npm install @better-auth/api-key
```

```typescript
import { apiKey } from "@better-auth/api-key";  // extracted package, not better-auth/plugins

export const auth = betterAuth({
  // ... other config
  plugins: [
    apiKey({
      // Enable API key authentication
      enabled: true,
    }),
  ],
});
```

Schema note: the `ApiKey.userId` field was renamed to `referenceId` and a new
`configId` field (defaults to `"default"`) was added. Run `npx auth migrate`
after upgrading.

---

## TypeScript Configuration

### tsconfig.json

```json
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ESNext",
    "moduleResolution": "bundler",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "types": ["@cloudflare/workers-types"]
  }
}
```

### Type Definitions

```typescript
// src/types/env.d.ts
export interface Env {
  DB: D1Database;
  BETTER_AUTH_SECRET: string;
  BETTER_AUTH_URL: string;
  GOOGLE_CLIENT_ID?: string;
  GOOGLE_CLIENT_SECRET?: string;
  GITHUB_CLIENT_ID?: string;
  GITHUB_CLIENT_SECRET?: string;
}
```

---

## Dynamic Base URL (v1.5+)

Allowlist-based multi-domain support for Vercel previews, reverse proxies, multi-domain setups.

```typescript
export const auth = betterAuth({
    baseURL: {
        allowedHosts: [
            "myapp.com",
            "*.vercel.app",
            "preview-*.myapp.com",
            "localhost:3000",
        ],
        fallback: "https://myapp.com",
        protocol: "auto",
    },
});
```

`allowedHosts` are automatically added to `trustedOrigins`. Supports wildcard patterns (`*`).

---

## Secret Key Rotation (v1.5+)

Non-destructive rotation without invalidating existing sessions.

```typescript
export const auth = betterAuth({
    secrets: [
        { version: 2, value: "new-secret-key-at-least-32-chars" },
        { version: 1, value: "old-secret-key-still-used-to-decrypt" },
    ],
});
```

Or via env: `BETTER_AUTH_SECRETS="2:new-secret,1:old-secret"`

---

## Defer Session Refresh (v1.5+)

For read-replica database setups. GET becomes read-only, returns `needsRefresh: true`.

```typescript
export const auth = betterAuth({
    session: {
        deferSessionRefresh: true,
    },
});
```

---

## Verification on Secondary Storage (v1.5+)

Store verification tokens in Redis instead of the database.

```typescript
export const auth = betterAuth({
    secondaryStorage: { /* Redis config */ },
    verification: {
        storeIdentifier: "hashed",
        storeInDatabase: false,
    },
});
```

---

## Minimal Bundle (v1.5+)

Use `better-auth/minimal` with extracted adapter packages for smallest bundle:

```typescript
import { drizzleAdapter } from "@better-auth/drizzle-adapter";
import { betterAuth } from "better-auth/minimal";

export const auth = betterAuth({
    database: drizzleAdapter(db, { provider: "pg" }),
});
```

---

## D1 Native Support (v1.5+)

Pass D1 binding directly without Drizzle/Kysely:

```typescript
import { betterAuth } from "better-auth";

export default {
    async fetch(request, env) {
        const auth = betterAuth({
            database: env.DB,
        });
        return auth.handler(request);
    },
} satisfies ExportedHandler<{ DB: D1Database }>;
```

---

## Migration from v1.3.x

If upgrading from better-auth v1.3.x, see `migration-guide-1.4.0.md` for:
- ESM migration steps
- API rename changes
- Callback signature updates
- Breaking changes checklist

---

## Troubleshooting

### "Cannot use import statement outside a module"

**Cause**: Missing `"type": "module"` in package.json
**Fix**: Add to package.json: `{ "type": "module" }`

### CORS Errors

**Cause**: Missing `credentials: true` in CORS config
**Fix**: Ensure CORS middleware includes `credentials: true`

### Session Not Persisting

**Cause**: Cookie domain mismatch or missing CORS credentials
**Fix**:
1. Verify `baseURL` matches deployed domain
2. Ensure CORS `credentials: true`
3. Check cookie `SameSite` and `Secure` settings

### OAuth Redirect URI Mismatch

**Cause**: Callback URL doesn't match provider settings
**Fix**: Ensure exact match in provider settings:
- ✅ `https://yourdomain.com/api/auth/callback/google`
- ❌ `https://yourdomain.com/api/auth/callback/google/` (trailing slash)
- ❌ `http://yourdomain.com/api/auth/callback/google` (http vs https)

---

## Official Documentation

- **better-auth Docs**: https://better-auth.com
- **v1.4.0 Changelog**: https://www.better-auth.com/blog/1-4
- **Drizzle ORM**: https://orm.drizzle.team
- **Cloudflare D1**: https://developers.cloudflare.com/d1

---

**Last verified**: 2026-04-08 with better-auth@1.6.0
reverse-engineer-anythingmorluto/reaReverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis.Stars: 471kUpdated Claude CodeCodexVerifiedInstall
diagnosing-superpowersobra/superpowersUse when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness.Stars: 322kUpdated Claude CodeCodexVerifiedInstall
dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependenciesStars: 322kUpdated Claude CodeCodexVerifiedInstall
executing-plansobra/superpowersUse when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is availableStars: 322kUpdated Claude CodeCodexVerifiedInstall