Skip to content

Skills for Claude Code CLI such as full stack dev Cloudflare, React, Tailwind v4, and AI integrations.

better-auth v2.0.0 - BREAKING: Correct D1 adapter patterns (Drizzle/Kysely required)

Jez5a7c400c96f9
diff --git a/skills/better-auth/.claude-plugin/plugin.json b/skills/better-auth/.claude-plugin/plugin.json
index 58dea9bf..81bb0f2b 100644
--- a/skills/better-auth/.claude-plugin/plugin.json
+++ b/skills/better-auth/.claude-plugin/plugin.json
@@ -1,12 +1,12 @@
{
"name": "better-auth",
- "description": "Production-ready authentication framework for TypeScript with first-class Cloudflare D1 support. Use this skill when building auth systems as a self-hosted alternative to Clerk or Auth.js, particularly for Cloudflare Workers projects. Supports social providers (Google, GitHub, Microsoft, Apple), email/password, magic links, 2FA, passkeys, organizations, and RBAC. Prevents 10+ common authentication errors including session serialization issues, CORS misconfigurations, D1 adapter setup, social pro",
- "version": "1.0.0",
+ "description": "Production-ready authentication framework for TypeScript with Cloudflare D1 support via Drizzle ORM or Kysely. CRITICAL: better-auth requires Drizzle ORM or Kysely as adapters - there is NO direct d1Adapter. Use this skill when building auth systems as self-hosted alternative to Clerk or Auth.js for Cloudflare Workers. Supports social providers, email/password, magic links, 2FA, passkeys, organizations, RBAC. Prevents 12+ errors including D1 adapter misconfiguration, schema generation issues, session serialization, CORS, OAuth flows.",
+ "version": "2.0.0",
"author": {
"name": "Jeremy Dawes",
"email": "[email protected]"
},
"license": "MIT",
"repository": "https://github.com/jezweb/claude-skills",
- "keywords": ["better-auth","authentication","cloudflare d1 auth","self-hosted auth","typescript auth","clerk alternative","auth.js alternative","social login","oauth providers","session management","jwt tokens","2fa","two-factor","passkeys","webauthn"]
+ "keywords": ["better-auth","authentication","cloudflare d1 auth","drizzle orm auth","kysely auth","self-hosted auth","typescript auth","clerk alternative","auth.js alternative","social login","oauth providers","session management","jwt tokens","2fa","two-factor","passkeys","webauthn","drizzle d1","kysely d1"]
}
diff --git a/skills/better-auth/README.md b/skills/better-auth/README.md
index 45d42b6f..29b1bf68 100644
--- a/skills/better-auth/README.md
+++ b/skills/better-auth/README.md
@@ -6,7 +6,9 @@
## What This Skill Does
-Provides complete patterns for implementing authentication with **better-auth**, a comprehensive TypeScript auth framework. Includes first-class support for Cloudflare Workers + D1, making it an excellent self-hosted alternative to Clerk or Auth.js.
+Provides complete patterns for implementing authentication with **better-auth**, a comprehensive TypeScript auth framework. Includes support for Cloudflare Workers + D1 via **Drizzle ORM** or **Kysely** (no direct D1 adapter exists), making it an excellent self-hosted alternative to Clerk or Auth.js.
+
+**⚠️ v2.0.0 Breaking Change**: Previous skill version incorrectly documented a non-existent `d1Adapter()`. This version corrects all patterns to use Drizzle ORM or Kysely as required by better-auth.
---
@@ -63,8 +65,10 @@ This skill should be automatically invoked when you mention:
7. **Migration Guides** - From Clerk and Auth.js
8. **Database Setup** - D1 and PostgreSQL schema patterns
-### Errors Prevented (10 Common Issues)
+### Errors Prevented (12 Common Issues)
+- ✅ **D1 adapter misconfiguration** (no direct d1Adapter, must use Drizzle/Kysely)
+- ✅ **Schema generation failures** (using Drizzle Kit correctly)
- ✅ D1 eventual consistency causing stale session reads
- ✅ CORS misconfiguration for SPA applications
- ✅ Session serialization errors in Workers
@@ -89,23 +93,35 @@ This skill should be automatically invoked when you mention:
## Quick Example
-### Cloudflare Worker Setup
+### Cloudflare Worker Setup (Drizzle ORM)
+
+**⚠️ CRITICAL**: better-auth requires **Drizzle ORM** or **Kysely** for D1. There is NO direct `d1Adapter()`.
```typescript
import { betterAuth } from 'better-auth'
-import { d1Adapter } from 'better-auth/adapters/d1'
+import { drizzleAdapter } from 'better-auth/adapters/drizzle'
+import { drizzle } from 'drizzle-orm/d1'
import { Hono } from 'hono'
+import * as schema from './db/schema' // Your Drizzle schema
type Env = {
DB: D1Database
BETTER_AUTH_SECRET: string
+ GOOGLE_CLIENT_ID: string
+ GOOGLE_CLIENT_SECRET: string
}
const app = new Hono<{ Bindings: Env }>()
app.all('/api/auth/*', async (c) => {
+ // Initialize Drizzle with D1
+ const db = drizzle(c.env.DB, { schema })
+
const auth = betterAuth({
- database: d1Adapter(c.env.DB),
+ // Use Drizzle adapter with SQLite provider
+ database: drizzleAdapter(db, {
+ provider: "sqlite",
+ }),
secret: c.env.BETTER_AUTH_SECRET,
emailAndPassword: { enabled: true },
socialProviders: {
@@ -122,6 +138,13 @@ app.all('/api/auth/*', async (c) => {
export default app
```
+**Required dependencies**:
+```bash
+npm install better-auth drizzle-orm drizzle-kit @cloudflare/workers-types hono
+```
+
+**Complete setup guide**: See SKILL.md for full step-by-step instructions including schema definition, migrations, and deployment.
+
---
## Performance
@@ -187,9 +210,11 @@ npm install pg drizzle-orm
## Version Info
-- **Skill Version**: 1.0.0
+- **Skill Version**: 2.0.0 (Breaking Change - Corrected D1 adapter patterns)
- **Package Version**: [email protected]
-- **Last Verified**: 2025-10-31
+- **Kysely**: [email protected], @noxharmonium/[email protected]
+- **Last Verified**: 2025-11-08
- **Compatibility**: Node.js 18+, Bun 1.0+, Cloudflare Workers
---
diff --git a/skills/better-auth/SKILL.md b/skills/better-auth/SKILL.md
index 6ba674c6..b761f8ac 100644
--- a/skills/better-auth/SKILL.md
+++ b/skills/better-auth/SKILL.md
@@ -1,23 +1,26 @@
---
name: better-auth
description: |
- Production-ready authentication framework for TypeScript with first-class Cloudflare D1 support. Use this skill when building auth systems as a self-hosted alternative to Clerk or Auth.js, particularly for Cloudflare Workers projects. Supports social providers (Google, GitHub, Microsoft, Apple), email/password, magic links, 2FA, passkeys, organizations, and RBAC. Prevents 10+ common authentication errors including session serialization issues, CORS misconfigurations, D1 adapter setup, social provider OAuth flows, and JWT token handling.
+ Production-ready authentication framework for TypeScript with Cloudflare D1 support via Drizzle ORM or Kysely. Use this skill when building auth systems as a self-hosted alternative to Clerk or Auth.js, particularly for Cloudflare Workers projects. CRITICAL: better-auth requires Drizzle ORM or Kysely as database adapters - there is NO direct D1 adapter. Supports social providers (Google, GitHub, Microsoft, Apple), email/password, magic links, 2FA, passkeys, organizations, and RBAC. Prevents 12+ common authentication errors including D1 adapter misconfiguration, schema generation issues, session serialization, CORS, OAuth flows, and JWT token handling.
- Keywords: better-auth, authentication, cloudflare d1 auth, self-hosted auth, typescript auth, clerk alternative, auth.js alternative, social login, oauth providers, session management, jwt tokens, 2fa, two-factor, passkeys, webauthn, multi-tenant auth, organizations, teams, rbac, role-based access, google auth, github auth, microsoft auth, apple auth, magic links, email password, better-auth setup, session serialization error, cors auth, d1 adapter
+ Keywords: better-auth, authentication, cloudflare d1 auth, drizzle orm auth, kysely auth, self-hosted auth, typescript auth, clerk alternative, auth.js alternative, social login, oauth providers, session management, jwt tokens, 2fa, two-factor, passkeys, webauthn, multi-tenant auth, organizations, teams, rbac, role-based access, google auth, github auth, microsoft auth, apple auth, magic links, email password, better-auth setup, drizzle d1, kysely d1, session serialization error, cors auth, d1 adapter
license: MIT
metadata:
- version: 1.0.0
- last_verified: 2025-10-31
- production_tested: better-chatbot (852 stars, active deployment)
+ version: 2.0.0
+ last_verified: 2025-11-08
+ production_tested: multiple (better-chatbot, zpg6/better-auth-cloudflare, matthewlynch/better-auth-react-router-cloudflare-d1)
package_version: 1.3.34
token_savings: ~70%
- errors_prevented: 10
+ errors_prevented: 12
official_docs: https://better-auth.com
github: https://github.com/better-auth/better-auth
+ breaking_changes: v2.0.0 - Corrected D1 adapter patterns (Drizzle/Kysely required)
keywords:
- better-auth
- authentication
- cloudflare-d1
+ - drizzle-orm
+ - kysely
- self-hosted-auth
- typescript-auth
- clerk-alternative
@@ -44,48 +47,61 @@ allowed-tools:
## Overview
-**better-auth** is a comprehensive, framework-agnostic authentication and authorization library for TypeScript. It provides a complete auth solution with first-class support for Cloudflare D1, making it an excellent self-hosted alternative to Clerk or Auth.js.
+**better-auth** is a comprehensive, framework-agnostic authentication and authorization library for TypeScript. It provides a complete auth solution with support for Cloudflare D1 via **Drizzle ORM** or **Kysely**, making it an excellent self-hosted alternative to Clerk or Auth.js.
+
+**⚠️ CRITICAL: D1 Adapter Requirements**
+
+better-auth **DOES NOT** have a direct `d1Adapter()`. You **MUST** use either:
+1. **Drizzle ORM** (recommended) - `drizzleAdapter()`
+2. **Kysely** (alternative) - Kysely instance with D1Dialect
**Use this skill when**:
- Building authentication for Cloudflare Workers + D1 applications
- Need a self-hosted, vendor-independent auth solution
-- Migrating from Clerk (avoid vendor lock-in)
-- Upgrading from Auth.js (need more features)
+- Migrating from Clerk (avoid vendor lock-in and costs)
+- Upgrading from Auth.js (need more features like 2FA, organizations)
- Implementing multi-tenant SaaS with organizations/teams
-- Require advanced features: 2FA, passkeys, RBAC, social auth
+- Require advanced features: 2FA, passkeys, RBAC, social auth, rate limiting
-**Package**: `[email protected]` (latest verified 2025-10-31)
+**Package**: `[email protected]` (latest verified 2025-11-08)
---
## Installation
-### Core Package
+### Core Packages
+
+**Option 1: Drizzle ORM (Recommended)**
```bash
-npm install better-auth
+npm install better-auth drizzle-orm drizzle-kit
# or
-pnpm add better-auth
+pnpm add better-auth drizzle-orm drizzle-kit
+```
+
+**Option 2: Kysely**
+
+```bash
+npm install better-auth kysely @noxharmonium/kysely-d1
# or
-yarn add better-auth
+pnpm add better-auth kysely @noxharmonium/kysely-d1
```
-### Database Adapters
+### Additional Dependencies
-**For Cloudflare D1** (Workers):
+**For Cloudflare Workers**:
```bash
-npm install @cloudflare/workers-types
+npm install @cloudflare/workers-types hono
```
-**For PostgreSQL**:
+**For PostgreSQL** (via Hyperdrive):
```bash
npm install pg drizzle-orm
+# or with Kysely
+npm install kysely
```
-**For MySQL/SQLite**: Built-in adapters, no extra packages needed.
-
-### Social Providers (Optional)
-
+**Social Providers** (Optional):
```bash
npm install @better-auth/google
npm install @better-auth/github
@@ -94,194 +110,446 @@ npm install @better-auth/microsoft
---
-## Quick Start Patterns
-
-### Pattern 1: Cloudflare Workers + D1
-
-**Use when**: Building API on Cloudflare Workers with D1 database
-
-**File**: `src/worker.ts`
-```typescript
-import { betterAuth } from 'better-auth'
-import { d1Adapter } from 'better-auth/adapters/d1'
-import { Hono } from 'hono'
+## Quick Start: Cloudflare Workers + D1 + Drizzle
-type Env = {
- DB: D1Database
- BETTER_AUTH_SECRET: string
- GOOGLE_CLIENT_ID: string
- GOOGLE_CLIENT_SECRET: string
-}
+### Step 1: Create D1 Database
-const app = new Hono<{ Bindings: Env }>()
-
-// Auth routes handler
-app.all('/api/auth/*', async (c) => {
- const auth = betterAuth({
- database: d1Adapter(c.env.DB),
- secret: c.env.BETTER_AUTH_SECRET,
-
- // Basic auth methods
- emailAndPassword: {
- enabled: true,
- requireEmailVerification: true
- },
-
- // Social providers
- socialProviders: {
- google: {
- clientId: c.env.GOOGLE_CLIENT_ID,
- clientSecret: c.env.GOOGLE_CLIENT_SECRET
- }
- }
- })
-
- return auth.handler(c.req.raw)
-})
+```bash
+# Create database
+wrangler d1 create my-app-db
-export default app
+# Copy the database_id from output
```
-**wrangler.toml**:
+**Add to `wrangler.toml`**:
```toml
name = "my-app"
-main = "src/worker.ts"
-compatibility_date = "2024-01-01"
+compatibility_date = "2024-11-01"
+compatibility_flags = ["nodejs_compat"]
[[d1_databases]]
binding = "DB"
database_name = "my-app-db"
-database_id = "your-database-id"
+database_id = "your-database-id-here"
[vars]
-# Public vars here
+BETTER_AUTH_URL = "http://localhost:5173"
-# Secrets (use: wrangler secret put BETTER_AUTH_SECRET)
+# Secrets (use: wrangler secret put SECRET_NAME)
# - BETTER_AUTH_SECRET
# - GOOGLE_CLIENT_ID
# - GOOGLE_CLIENT_SECRET
```
-**Setup D1 Database**:
+---
+
+### Step 2: Define Database Schema
+
+**File**: `src/db/schema.ts`
+
+```typescript
+import { integer, sqliteTable, text } from "drizzle-orm/sqlite-core";
+import { sql } from "drizzle-orm";
+
+// better-auth core tables
+export const user = sqliteTable("user", {
+ id: text().primaryKey(),
+ name: text().notNull(),
+ email: text().notNull().unique(),
+ emailVerified: integer({ mode: "boolean" }).notNull().default(false),
+ image: text(),
+ createdAt: integer({ mode: "timestamp" })
+ .notNull()
+ .default(sql`(unixepoch())`),
+ updatedAt: integer({ mode: "timestamp" })
+ .notNull()
+ .default(sql`(unixepoch())`),
+});
+
+export const session = sqliteTable("session", {
+ id: text().primaryKey(),
+ userId: text()
+ .notNull()
+ .references(() => user.id, { onDelete: "cascade" }),
+ token: text().notNull(),
+ expiresAt: integer({ mode: "timestamp" }).notNull(),
+ ipAddress: text(),
+ userAgent: text(),
+ createdAt: integer({ mode: "timestamp" })
+ .notNull()
+ .default(sql`(unixepoch())`),
+ updatedAt: integer({ mode: "timestamp" })
+ .notNull()
+ .default(sql`(unixepoch())`),
+});
+
+export const account = sqliteTable("account", {
+ id: text().primaryKey(),
+ userId: text()
+ .notNull()
+ .references(() => user.id, { onDelete: "cascade" }),
+ accountId: text().notNull(),
+ providerId: text().notNull(),
+ accessToken: text(),
+ refreshToken: text(),
+ accessTokenExpiresAt: integer({ mode: "timestamp" }),
+ refreshTokenExpiresAt: integer({ mode: "timestamp" }),
+ scope: text(),
+ idToken: text(),
+ password: text(),
+ createdAt: integer({ mode: "timestamp" })
+ .notNull()
+ .default(sql`(unixepoch())`),
+ updatedAt: integer({ mode: "timestamp" })
+ .notNull()
+ .default(sql`(unixepoch())`),
+});
+
+export const verification = sqliteTable("verification", {
+ id: text().primaryKey(),
+ identifier: text().notNull(),
+ value: text().notNull(),
+ expiresAt: integer({ mode: "timestamp" }).notNull(),
+ createdAt: integer({ mode: "timestamp" })
+ .notNull()
+ .default(sql`(unixepoch())`),
+ updatedAt: integer({ mode: "timestamp" })
+ .notNull()
+ .default(sql`(unixepoch())`),
+});
+
+// Add your custom tables here
+export const profile = sqliteTable("profile", {
+ id: text().primaryKey(),
+ userId: text()
+ .notNull()
+ .references(() => user.id, { onDelete: "cascade" }),
+ bio: text(),
+ website: text(),
+});
+```
+
+---
+
+### Step 3: Configure Drizzle
+
+**File**: `drizzle.config.ts`
+
+```typescript
+import type { Config } from "drizzle-kit";
+
+export default {
+ out: "./drizzle",
+ schema: "./src/db/schema.ts",
+ dialect: "sqlite",
+ driver: "d1-http",
+ dbCredentials: {
+ databaseId: process.env.CLOUDFLARE_DATABASE_ID!,
+ accountId: process.env.CLOUDFLARE_ACCOUNT_ID!,
+ token: process.env.CLOUDFLARE_TOKEN!,
+ },
+} satisfies Config;
+```
+
+**Create `.env` file** (for migrations):
+```env
+CLOUDFLARE_ACCOUNT_ID=your-account-id
+CLOUDFLARE_DATABASE_ID=your-database-id
+CLOUDFLARE_TOKEN=your-api-token
+```
+
+---
+
+### Step 4: Generate and Apply Migrations
+
```bash
-# Create database
-wrangler d1 create my-app-db
+# Generate migration from schema
+npx drizzle-kit generate
-# Generate migration SQL from better-auth
-npx better-auth migrate --database d1
+# Apply migration to D1 (local)
+wrangler d1 migrations apply my-app-db --local
-# Apply migration
-wrangler d1 execute my-app-db --remote --file migrations/0001_initial.sql
+# Apply migration to D1 (production)
+wrangler d1 migrations apply my-app-db --remote
```
---
-### Pattern 2: Next.js API Route
+### Step 5: Initialize Database and Auth
-**Use when**: Building traditional Next.js app with PostgreSQL or D1
+**File**: `src/db/index.ts`
-**File**: `src/lib/auth.ts`
```typescript
-import { betterAuth } from 'better-auth'
-import { Pool } from 'pg'
+import { drizzle } from "drizzle-orm/d1";
+import * as schema from "./schema";
-export const auth = betterAuth({
- database: new Pool({
- connectionString: process.env.DATABASE_URL
- }),
+export type Database = ReturnType<typeof createDatabase>;
- secret: process.env.BETTER_AUTH_SECRET!,
+export function createDatabase(d1: D1Database) {
+ return drizzle(d1, { schema });
+}
+```
- emailAndPassword: {
- enabled: true,
- requireEmailVerification: true,
- sendVerificationEmail: async ({ user, url }) => {
- // Send email with verification link
- await sendEmail({
- to: user.email,
- subject: 'Verify your email',
- html: `Click <a href="${url}">here</a> to verify`
- })
- }
- },
+**File**: `src/auth.ts`
+
+```typescript
+import { betterAuth } from "better-auth";
+import { drizzleAdapter } from "better-auth/adapters/drizzle";
+import type { Database } from "./db";
- socialProviders: {
- google: {
- clientId: process.env.GOOGLE_CLIENT_ID!,
- clientSecret: process.env.GOOGLE_CLIENT_SECRET!
+type 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;
+};
+
+export function createAuth(db: Database, env: Env) {
+ return betterAuth({
+ baseURL: env.BETTER_AUTH_URL,
+ secret: env.BETTER_AUTH_SECRET,
+
+ // Drizzle adapter with SQLite provider
+ database: drizzleAdapter(db, {
+ provider: "sqlite",
+ }),
+
+ // Email/password authentication
+ emailAndPassword: {
+ enabled: true,
+ requireEmailVerification: true,
+ sendVerificationEmail: async ({ user, url, token }) => {
+ // TODO: Implement email sending
+ // Use Resend, SendGrid, or Cloudflare Email Routing
+ console.log(`Verification email for ${user.email}: ${url}`);
+ },
},
- github: {
- clientId: process.env.GITHUB_CLIENT_ID!,
- clientSecret: process.env.GITHUB_CLIENT_SECRET!
- }
- },
- // Advanced features via plugins
- plugins: [
- twoFactor(),
- organization(),
- rateLimit()
- ]
-})
+ // Social providers
+ socialProviders: {
+ google: env.GOOGLE_CLIENT_ID
+ ? {
+ clientId: env.GOOGLE_CLIENT_ID,
+ clientSecret: env.GOOGLE_CLIENT_SECRET!,
+ scope: ["openid", "email", "profile"],
+ }
+ : undefined,
+ github: env.GITHUB_CLIENT_ID
+ ? {
+ clientId: env.GITHUB_CLIENT_ID,
+ clientSecret: env.GITHUB_CLIENT_SECRET!,
+ scope: ["user:email", "read:user"],
+ }
+ : undefined,
+ },
+
+ // Session configuration
+ session: {
+ expiresIn: 60 * 60 * 24 * 7, // 7 days
+ updateAge: 60 * 60 * 24, // Update every 24 hours
+ },
+ });
+}
```
-**File**: `src/app/api/auth/[...all]/route.ts`
+---
+
+### Step 6: Create Worker with Auth Routes
+
+**File**: `src/index.ts`
+
```typescript
-import { auth } from '@/lib/auth'
+import { Hono } from "hono";
+import { cors } from "hono/cors";
+import { createDatabase } from "./db";
+import { createAuth } from "./auth";
+
+type 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;
+};
+
+const app = new Hono<{ Bindings: Env }>();
+
+// CORS for frontend
+app.use(
+ "/api/*",
+ cors({
+ origin: ["http://localhost:3000", "https://yourdomain.com"],
+ credentials: true,
+ allowMethods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
+ allowHeaders: ["Content-Type", "Authorization"],
+ })
+);
+
+// Auth routes - handle all better-auth endpoints
+app.all("/api/auth/*", async (c) => {
+ const db = createDatabase(c.env.DB);
+ const auth = createAuth(db, c.env);
+ return auth.handler(c.req.raw);
+});
+
+// Example: Protected API route
+app.get("/api/protected", async (c) => {
+ const db = createDatabase(c.env.DB);
+ const auth = createAuth(db, c.env);
+ const session = await auth.api.getSession({
+ headers: c.req.raw.headers,
+ });
+
+ if (!session) {
+ return c.json({ error: "Unauthorized" }, 401);
+ }
+
+ return c.json({
+ message: "Protected data",
+ user: session.user,
+ });
+});
+
+// Health check
+app.get("/health", (c) => c.json({ status: "ok" }));
+
+export default app;
+```
+
+---
+
+### Step 7: Set Secrets
+
+```bash
+# Generate a random secret
+openssl rand -base64 32
+
+# Set secrets in Wrangler
+wrangler secret put BETTER_AUTH_SECRET
+# Paste the generated secret
+
+# Optional: Set OAuth secrets
+wrangler secret put GOOGLE_CLIENT_ID
+wrangler secret put GOOGLE_CLIENT_SECRET
+wrangler secret put GITHUB_CLIENT_ID
+wrangler secret put GITHUB_CLIENT_SECRET
+```
+
+---
+
+### Step 8: Deploy
-export const GET = auth.handler
-export const POST = auth.handler
+```bash
+# Test locally
+npm run dev
+
+# Deploy to Cloudflare
+wrangler deploy
```
---
-### Pattern 3: React Client Integration
+## Alternative: Kysely Adapter Pattern
+
+If you prefer Kysely over Drizzle:
+
+**File**: `src/auth.ts`
+
+```typescript
+import { betterAuth } from "better-auth";
+import { Kysely, CamelCasePlugin } from "kysely";
+import { D1Dialect } from "@noxharmonium/kysely-d1";
+
+type Env = {
+ DB: D1Database;
+ BETTER_AUTH_SECRET: string;
+ // ... other env vars
+};
+
+export function createAuth(env: Env) {
+ return betterAuth({
+ secret: env.BETTER_AUTH_SECRET,
+
+ // Kysely with D1Dialect
+ database: {
+ db: new Kysely({
+ dialect: new D1Dialect({
+ database: env.DB,
+ }),
+ plugins: [
+ // CRITICAL: Required if using Drizzle schema with snake_case
+ new CamelCasePlugin(),
+ ],
+ }),
+ type: "sqlite",
+ },
+
+ emailAndPassword: {
+ enabled: true,
+ },
+
+ // ... other config
+ });
+}
+```
+
+**Why CamelCasePlugin?**
+
+If your Drizzle schema uses `snake_case` column names (e.g., `email_verified`), but better-auth expects `camelCase` (e.g., `emailVerified`), the `CamelCasePlugin` automatically converts between the two.
+
+---
-**Use when**: Need client-side auth state and actions
+## Client Integration (React)
**File**: `src/lib/auth-client.ts`
+
```typescript
-import { createAuthClient } from 'better-auth/client'
+import { createAuthClient } from "better-auth/client";
export const authClient = createAuthClient({
- baseURL: process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000'
-})
+ baseURL: import.meta.env.VITE_API_URL || "http://localhost:8787",
+});
```
**File**: `src/components/LoginForm.tsx`
+
```typescript
-'use client'
+"use client";
-import { authClient } from '@/lib/auth-client'
-import { useState } from 'react'
+import { authClient } from "@/lib/auth-client";
+import { useState } from "react";
export function LoginForm() {
- const [email, setEmail] = useState('')
- const [password, setPassword] = useState('')
+ const [email, setEmail] = useState("");
+ const [password, setPassword] = useState("");
const handleSubmit = async (e: React.FormEvent) => {
- e.preventDefault()
+ e.preventDefault();
const { data, error } = await authClient.signIn.email({
email,
- password
- })
+ password,
+ });
if (error) {
- console.error('Login failed:', error)
- return
+ console.error("Login failed:", error);
+ return;
}
- // Redirect or update UI
- window.location.href = '/dashboard'
- }
+ window.location.href = "/dashboard";
+ };
const handleGoogleSignIn = async () => {
await authClient.signIn.social({
- provider: 'google',
- callbackURL: '/dashboard'
- })
- }
+ provider: "google",
+ callbackURL: "/dashboard",
+ });
+ };
return (
<form onSubmit={handleSubmit}>
@@ -302,81 +570,28 @@ export function LoginForm() {
Sign in with Google
</button>
</form>
- )
+ );
}
```
-**Use React Hook** (if you have a session endpoint):
+**Use React Hook**:
```typescript
-'use client'
+"use client";
-import { useSession } from 'better-auth/client'
+import { authClient } from "@/lib/auth-client";
export function UserProfile() {
- const { data: session, isPending } = useSession()
+ const { data: session, isPending } = authClient.useSession();
- if (isPending) return <div>Loading...</div>
- if (!session) return <div>Not authenticated</div>
+ if (isPending) return <div>Loading...</div>;
+ if (!session) return <div>Not authenticated</div>;
return (
<div>
<p>Welcome, {session.user.email}</p>
- <button onClick={() => authClient.signOut()}>
- Sign Out
- </button>
+ <button onClick={() => authClient.signOut()}>Sign Out</button>
</div>
- )
-}
-```
-
----
-
-### Pattern 4: Protected API Route (Middleware)
-
-**Use when**: Need to verify session in API routes
-
-**Cloudflare Workers**:
-```typescript
-import { betterAuth } from 'better-auth'
-import { d1Adapter } from 'better-auth/adapters/d1'
-
-app.get('/api/protected', async (c) => {
- const auth = betterAuth({
- database: d1Adapter(c.env.DB),
- secret: c.env.BETTER_AUTH_SECRET
- })
-
- const session = await auth.getSession(c.req.raw)
-
- if (!session) {
- return c.json({ error: 'Unauthorized' }, 401)
- }
-
- return c.json({
- message: 'Protected data',
- user: session.user
- })
-})
-```
-
-**Next.js Middleware**:
-```typescript
-// middleware.ts
-import { NextRequest, NextResponse } from 'next/server'
-import { auth } from '@/lib/auth'
-
-export async function middleware(request: NextRequest) {
- const session = await auth.getSession(request)
-
- if (!session && request.nextUrl.pathname.startsWith('/dashboard')) {
- return NextResponse.redirect(new URL('/login', request.url))
- }
-
- return NextResponse.next()
-}
-
-export const config = {
- matcher: ['/dashboard/:path*']
+ );
}
```
@@ -387,31 +602,31 @@ export const config = {
### Two-Factor Authentication (2FA)
```typescript
-import { betterAuth } from 'better-auth'
-import { twoFactor } from 'better-auth/plugins'
+import { betterAuth } from "better-auth";
+import { twoFactor } from "better-auth/plugins";
export const auth = betterAuth({
database: /* ... */,
plugins: [
twoFactor({
- methods: ['totp', 'sms'], // Time-based or SMS
- issuer: 'MyApp'
- })
- ]
-})
+ methods: ["totp", "sms"],
+ issuer: "MyApp",
+ }),
+ ],
+});
```
**Client**:
```typescript
-// Enable 2FA for user
+// Enable 2FA
const { data, error } = await authClient.twoFactor.enable({
- method: 'totp'
-})
+ method: "totp",
+});
// Verify code
await authClient.twoFactor.verify({
- code: '123456'
-})
+ code: "123456",
+});
```
---
@@ -419,471 +634,234 @@ await authClient.twoFactor.verify({
### Organizations & Teams
```typescript
-import { betterAuth } from 'better-auth'
-import { organization } from 'better-auth/plugins'
+import { betterAuth } from "better-auth";
+import { organization } from "better-auth/plugins";
export const auth = betterAuth({
database: /* ... */,
plugins: [
organization({
- roles: ['owner', 'admin', 'member'],
+ roles: ["owner", "admin", "member"],
permissions: {
- admin: ['read', 'write', 'delete'],
- member: ['read']
- }
- })
- ]
-})
+ admin: ["read", "write", "delete"],
+ member: ["read"],
+ },
+ }),
+ ],
+});
```
**Client**:
```typescript
// Create organization
await authClient.organization.create({
- name: 'Acme Corp',
- slug: 'acme'
-})
+ name: "Acme Corp",
+ slug: "acme",
+});
// Invite member
await authClient.organization.inviteMember({
- organizationId: 'org_123',
- email: '[email protected]',
- role: 'member'
-})
+ organizationId: "org_123",
+ email: "[email protected]",
+ role: "member",
+});
// Check permissions
const canDelete = await authClient.organization.hasPermission({
- organizationId: 'org_123',
- permission: 'delete'
-})
+ organizationId: "org_123",
+ permission: "delete",
+});
```
---
-### Multi-Tenant SaaS
+### Rate Limiting with KV
```typescript
-import { betterAuth } from 'better-auth'
-import { multiTenant } from 'better-auth/plugins'
-
-export const auth = betterAuth({
- database: /* ... */,
- plugins: [
- multiTenant({
- tenantIdHeader: 'x-tenant-id',
- isolateData: true // Ensure tenant data isolation
- })
- ]
-})
-```
+import { betterAuth } from "better-auth";
+import { rateLimit } from "better-auth/plugins";
----
-
-### Rate Limiting
-
-```typescript
-import { betterAuth } from 'better-auth'
-import { rateLimit } from 'better-auth/plugins'
-
-export const auth = betterAuth({
- database: /* ... */,
- plugins: [
- rateLimit({
- window: 60, // 60 seconds
- max: 5, // 5 requests per window
- storage: 'database' // or 'memory'
- })
- ]
-})
-```
-
-**For Cloudflare**: Use KV for distributed rate limiting:
-```typescript
-import { rateLimit } from 'better-auth/plugins'
-
-plugins: [
- rateLimit({
- window: 60,
- max: 5,
- storage: {
- get: async (key) => {
- return await c.env.RATE_LIMIT_KV.get(key)
- },
- set: async (key, value, ttl) => {
- await c.env.RATE_LIMIT_KV.put(key, value, { expirationTtl: ttl })
- }
- }
- })
-]
-```
-
----
-
-## Database Setup
-
-### D1 Schema Migration
-
-```bash
-# Generate migration
-npx better-auth migrate --database d1
-
-# This creates: migrations/0001_initial.sql
-```
-
-**Apply migration**:
-```bash
-# Local
-wrangler d1 execute my-app-db --local --file migrations/0001_initial.sql
-
-# Production
-wrangler d1 execute my-app-db --remote --file migrations/0001_initial.sql
-```
-
-**Manual schema** (if needed):
-```sql
--- better-auth core tables
-CREATE TABLE users (
- id TEXT PRIMARY KEY,
- email TEXT UNIQUE NOT NULL,
- emailVerified INTEGER DEFAULT 0,
- name TEXT,
- image TEXT,
- createdAt INTEGER NOT NULL,
- updatedAt INTEGER NOT NULL
-);
-
-CREATE TABLE sessions (
- id TEXT PRIMARY KEY,
- userId TEXT NOT NULL,
- expiresAt INTEGER NOT NULL,
- ipAddress TEXT,
- userAgent TEXT,
- FOREIGN KEY (userId) REFERENCES users(id) ON DELETE CASCADE
-);
-
-CREATE TABLE accounts (
- id TEXT PRIMARY KEY,
- userId TEXT NOT NULL,
- provider TEXT NOT NULL,
- providerAccountId TEXT NOT NULL,
- accessToken TEXT,
- refreshToken TEXT,
- expiresAt INTEGER,
- FOREIGN KEY (userId) REFERENCES users(id) ON DELETE CASCADE
-);
-
-CREATE TABLE verification_tokens (
- identifier TEXT NOT NULL,
- token TEXT NOT NULL,
- expires INTEGER NOT NULL,
- PRIMARY KEY (identifier, token)
-);
-
--- Additional tables for plugins (organizations, 2FA, etc.)
-```
-
----
-
-### PostgreSQL with Drizzle
-
-**File**: `src/db/schema.ts`
-```typescript
-import { pgTable, text, timestamp, boolean } from 'drizzle-orm/pg-core'
-
-export const users = pgTable('users', {
- id: text('id').primaryKey(),
- email: text('email').unique().notNull(),
- emailVerified: boolean('email_verified').default(false),
- name: text('name'),
- image: text('image'),
- createdAt: timestamp('created_at').notNull().defaultNow(),
- updatedAt: timestamp('updated_at').notNull().defaultNow()
-})
-
-// ... other tables
-```
-
-**Setup**:
-```typescript
-import { drizzle } from 'drizzle-orm/postgres-js'
-import postgres from 'postgres'
-import { betterAuth } from 'better-auth'
-
-const client = postgres(process.env.DATABASE_URL!)
-const db = drizzle(client)
-
-export const auth = betterAuth({
- database: db,
+type Env = {
+ DB: D1Database;
+ RATE_LIMIT_KV: KVNamespace;
// ...
-})
-```
-
----
-
-## Social Provider Setup
-
-### Google OAuth
-
-1. **Create OAuth credentials**: https://console.cloud.google.com/apis/credentials
-2. **Authorized redirect URI**: `https://yourdomain.com/api/auth/callback/google`
-3. **Environment variables**:
- ```env
- GOOGLE_CLIENT_ID=your-client-id
- GOOGLE_CLIENT_SECRET=your-client-secret
- ```
-
-**Configuration**:
-```typescript
-socialProviders: {
- google: {
- clientId: process.env.GOOGLE_CLIENT_ID!,
- clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
- scope: ['email', 'profile'] // Optional
- }
+};
+
+export function createAuth(db: Database, env: Env) {
+ return betterAuth({
+ database: drizzleAdapter(db, { provider: "sqlite" }),
+ plugins: [
+ rateLimit({
+ window: 60, // 60 seconds
+ max: 10, // 10 requests per window
+ storage: {
+ get: async (key) => {
+ return await env.RATE_LIMIT_KV.get(key);
+ },
+ set: async (key, value, ttl) => {
+ await env.RATE_LIMIT_KV.put(key, value, {
+ expirationTtl: ttl,
+ });
+ },
+ },
+ }),
+ ],
+ });
}
```
---
-### GitHub OAuth
-
-1. **Create OAuth app**: https://github.com/settings/developers
-2. **Authorization callback URL**: `https://yourdomain.com/api/auth/callback/github`
-3. **Environment variables**:
- ```env
- GITHUB_CLIENT_ID=your-client-id
- GITHUB_CLIENT_SECRET=your-client-secret
- ```
-
-**Configuration**:
-```typescript
-socialProviders: {
- github: {
- clientId: process.env.GITHUB_CLIENT_ID!,
- clientSecret: process.env.GITHUB_CLIENT_SECRET!
- }
-}
-```
+## Known Issues & Solutions
----
+### Issue 1: "d1Adapter is not exported" Error
-### Microsoft OAuth
+**Problem**: Code shows `import { d1Adapter } from 'better-auth/adapters/d1'` but this doesn't exist.
-```bash
-npm install @better-auth/microsoft
-```
+**Symptoms**: TypeScript error or runtime error about missing export.
-1. **Azure Portal**: https://portal.azure.com → App registrations
-2. **Redirect URI**: `https://yourdomain.com/api/auth/callback/microsoft`
-3. **Environment variables**:
- ```env
- MICROSOFT_CLIENT_ID=your-client-id
- MICROSOFT_CLIENT_SECRET=your-client-secret
- MICROSOFT_TENANT_ID=common # or your tenant ID
- ```
+**Solution**: Use Drizzle or Kysely instead:
-**Configuration**:
```typescript
-import { microsoft } from '@better-auth/microsoft'
-
-socialProviders: {
- microsoft: microsoft({
- clientId: process.env.MICROSOFT_CLIENT_ID!,
- clientSecret: process.env.MICROSOFT_CLIENT_SECRET!,
- tenantId: process.env.MICROSOFT_TENANT_ID!
- })
+// ❌ WRONG - This doesn't exist
+import { d1Adapter } from 'better-auth/adapters/d1'
+database: d1Adapter(env.DB)
+
+// ✅ CORRECT - Use Drizzle
+import { drizzleAdapter } from 'better-auth/adapters/drizzle'
+import { drizzle } from 'drizzle-orm/d1'
+const db = drizzle(env.DB, { schema })
+database: drizzleAdapter(db, { provider: "sqlite" })
+
+// ✅ CORRECT - Use Kysely
+import { Kysely } from 'kysely'
+import { D1Dialect } from '@noxharmonium/kysely-d1'
+database: {
+ db: new Kysely({ dialect: new D1Dialect({ database: env.DB }) }),
+ type: "sqlite"
}
```
+**Source**: Verified from 4 production repositories using better-auth + D1
+
---
-## Migration Guides
+### Issue 2: Schema Generation Fails
-### From Clerk
+**Problem**: `npx better-auth migrate` doesn't create D1-compatible schema.
-**Key differences**:
-- Clerk: Third-party service → better-auth: Self-hosted
-- Clerk: Proprietary → better-auth: Open source
-- Clerk: Monthly cost → better-auth: Free
+**Symptoms**: Migration SQL has wrong syntax or doesn't work with D1.
-**Migration steps**:
+**Solution**: Use Drizzle Kit to generate migrations:
-1. **Export user data** from Clerk (CSV or API)
-2. **Import into better-auth database**:
- ```typescript
- // migration script
- const clerkUsers = await fetchClerkUsers()
+```bash
+# Generate migration from Drizzle schema
+npx drizzle-kit generate
- for (const clerkUser of clerkUsers) {
- await db.insert(users).values({
- id: clerkUser.id,
- email: clerkUser.email,
- emailVerified: clerkUser.email_verified,
- name: clerkUser.first_name + ' ' + clerkUser.last_name,
- image: clerkUser.profile_image_url
- })
- }
- ```
-3. **Replace Clerk SDK** with better-auth client:
- ```typescript
- // Before (Clerk)
- import { useUser } from '@clerk/nextjs'
- const { user } = useUser()
+# Apply to D1
+wrangler d1 migrations apply my-app-db --remote
+```
- // After (better-auth)
- import { useSession } from 'better-auth/client'
- const { data: session } = useSession()
- const user = session?.user
- ```
-4. **Update middleware** for session verification
-5. **Configure social providers** (same OAuth apps, different config)
+**Why**: Drizzle Kit generates SQLite-compatible SQL that works with D1.
---
-### From Auth.js (NextAuth)
-
-**Key differences**:
-- Auth.js: Limited features → better-auth: Comprehensive (2FA, orgs, etc.)
-- Auth.js: Callbacks-heavy → better-auth: Plugin-based
-- Auth.js: Session handling varies → better-auth: Consistent
+### Issue 3: "CamelCase" vs "snake_case" Column Mismatch
-**Migration steps**:
+**Problem**: Database has `email_verified` but better-auth expects `emailVerified`.
-1. **Database schema**: Auth.js and better-auth use similar schemas, but column names differ
- ```sql
- -- Map Auth.js to better-auth
- ALTER TABLE users RENAME COLUMN emailVerified TO email_verified;
- -- etc.
- ```
-2. **Replace configuration**:
- ```typescript
- // Before (Auth.js)
- import NextAuth from 'next-auth'
- import GoogleProvider from 'next-auth/providers/google'
+**Symptoms**: Session reads fail, user data missing fields.
- export default NextAuth({
- providers: [GoogleProvider({ /* ... */ })]
- })
+**Solution**: Use `CamelCasePlugin` with Kysely or configure Drizzle properly:
- // After (better-auth)
- import { betterAuth } from 'better-auth'
+**With Kysely**:
+```typescript
+import { CamelCasePlugin } from "kysely";
- export const auth = betterAuth({
- socialProviders: {
- google: { /* ... */ }
- }
- })
- ```
-3. **Update client hooks**:
- ```typescript
- // Before
- import { useSession } from 'next-auth/react'
+new Kysely({
+ dialect: new D1Dialect({ database: env.DB }),
+ plugins: [new CamelCasePlugin()], // Converts between naming conventions
+})
+```
- // After
- import { useSession } from 'better-auth/client'
- ```
+**With Drizzle**: Define schema with camelCase from the start (as shown in examples).
---
-## Known Issues & Solutions
-
-### Issue 1: D1 Eventual Consistency
+### Issue 4: D1 Eventual Consistency
-**Problem**: Session reads immediately after write may return stale data in D1.
+**Problem**: Session reads immediately after write return stale data.
**Symptoms**: User logs in but `getSession()` returns null on next request.
**Solution**: Use Cloudflare KV for session storage (strong consistency):
-```typescript
-import { betterAuth } from 'better-auth'
-export const auth = betterAuth({
- database: d1Adapter(env.DB), // Users, accounts
- session: {
- storage: {
- get: async (sessionId) => {
- const session = await env.SESSIONS_KV.get(sessionId)
- return session ? JSON.parse(session) : null
- },
- set: async (sessionId, session, ttl) => {
- await env.SESSIONS_KV.put(
- sessionId,
- JSON.stringify(session),
- { expirationTtl: ttl }
- )
+```typescript
+import { betterAuth } from "better-auth";
+
+export function createAuth(db: Database, env: Env) {
+ return betterAuth({
+ database: drizzleAdapter(db, { provider: "sqlite" }),
+ session: {
+ storage: {
+ get: async (sessionId) => {
+ const session = await env.SESSIONS_KV.get(sessionId);
+ return session ? JSON.parse(session) : null;
+ },
+ set: async (sessionId, session, ttl) => {
+ await env.SESSIONS_KV.put(sessionId, JSON.stringify(session), {
+ expirationTtl: ttl,
+ });
+ },
+ delete: async (sessionId) => {
+ await env.SESSIONS_KV.delete(sessionId);
+ },
},
- delete: async (sessionId) => {
- await env.SESSIONS_KV.delete(sessionId)
- }
- }
- }
-})
+ },
+ });
+}
```
-**Source**: https://github.com/better-auth/better-auth/issues/147
+**Add to `wrangler.toml`**:
+```toml
+[[kv_namespaces]]
+binding = "SESSIONS_KV"
+id = "your-kv-namespace-id"
+```
---
-### Issue 2: CORS for SPA Applications
+### Issue 5: CORS Errors for SPA Applications
**Problem**: CORS errors when auth API is on different origin than frontend.
**Symptoms**: `Access-Control-Allow-Origin` errors in browser console.
**Solution**: Configure CORS headers in Worker:
-```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, // Allow cookies
- allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS']
-}))
-
-app.all('/api/auth/*', async (c) => {
- const auth = betterAuth({ /* ... */ })
- return auth.handler(c.req.raw)
-})
-```
-
-**Source**: https://better-auth.com/docs/guides/cors
----
-
-### Issue 3: Session Serialization in Workers
-
-**Problem**: Can't serialize complex session objects in Cloudflare Workers.
-
-**Symptoms**: `DataCloneError` or session data missing.
-
-**Solution**: Keep session data minimal and JSON-serializable:
```typescript
-export const auth = betterAuth({
- database: d1Adapter(env.DB),
- session: {
- // Only include serializable fields
- fields: {
- userId: true,
- email: true,
- role: true
- // Don't include: functions, Dates, complex objects
- }
- }
-})
+import { cors } from "hono/cors";
+
+app.use(
+ "/api/auth/*",
+ cors({
+ origin: ["https://yourdomain.com", "http://localhost:3000"],
+ credentials: true, // Allow cookies
+ allowMethods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
+ })
+);
```
---
-### Issue 4: OAuth Redirect URI Mismatch
+### Issue 6: OAuth Redirect URI Mismatch
**Problem**: Social sign-in fails with "redirect_uri_mismatch" error.
**Symptoms**: Google/GitHub OAuth returns error after user consent.
**Solution**: Ensure exact match in OAuth provider settings:
+
```
Provider setting: https://yourdomain.com/api/auth/callback/google
better-auth URL: https://yourdomain.com/api/auth/callback/google
@@ -895,19 +873,40 @@ better-auth URL: https://yourdomain.com/api/auth/callback/google
**Check better-auth callback URL**:
```typescript
// It's always: {baseURL}/api/auth/callback/{provider}
-const callbackURL = `${process.env.NEXT_PUBLIC_API_URL}/api/auth/callback/google`
-console.log('Configure this URL in Google Console:', callbackURL)
+const callbackURL = `${env.BETTER_AUTH_URL}/api/auth/callback/google`;
+console.log("Configure this URL in Google Console:", callbackURL);
+```
+
+---
+
+### Issue 7: Missing Dependencies
+
+**Problem**: TypeScript errors or runtime errors about missing packages.
+
+**Symptoms**: `Cannot find module 'drizzle-orm'` or similar.
+
+**Solution**: Install all required packages:
+
+**For Drizzle approach**:
+```bash
+npm install better-auth drizzle-orm drizzle-kit @cloudflare/workers-types
+```
+
+**For Kysely approach**:
+```bash
+npm install better-auth kysely @noxharmonium/kysely-d1 @cloudflare/workers-types
```
---
-### Issue 5: Email Verification Not Sending
+### Issue 8: Email Verification Not Sending
**Problem**: Email verification links never arrive.
**Symptoms**: User signs up, but no email received.
**Solution**: Implement `sendVerificationEmail` handler:
+
```typescript
export const auth = betterAuth({
database: /* ... */,
@@ -918,170 +917,127 @@ export const auth = betterAuth({
// Use your email service (SendGrid, Resend, etc.)
await sendEmail({
to: user.email,
- subject: 'Verify your email',
+ subject: "Verify your email",
html: `
<p>Click the link below to verify your email:</p>
<a href="${url}">Verify Email</a>
<p>Or use this code: ${token}</p>
- `
- })
- }
- }
-})
+ `,
+ });
+ },
+ },
+});
```
**For Cloudflare**: Use Cloudflare Email Routing or external service (Resend, SendGrid).
---
-### Issue 6: JWT Token Expiration
+### Issue 9: Session Expires Too Quickly
-**Problem**: Session expires too quickly or never expires.
+**Problem**: Session expires unexpectedly or never expires.
**Symptoms**: User logged out unexpectedly or session persists after logout.
**Solution**: Configure session expiration:
+
```typescript
export const auth = betterAuth({
database: /* ... */,
session: {
expiresIn: 60 * 60 * 24 * 7, // 7 days (in seconds)
- updateAge: 60 * 60 * 24 // Update session every 24 hours
- }
-})
-```
-
----
-
-### Issue 7: Password Hashing Performance
-
-**Problem**: Sign-up/login slow on Cloudflare Workers.
-
-**Symptoms**: Auth requests take >1 second.
-
-**Solution**: better-auth uses bcrypt by default, which is CPU-intensive. For Workers, ensure proper async handling:
-```typescript
-// better-auth handles this internally, but if custom:
-import bcrypt from 'bcryptjs'
-
-// Use async version (not sync)
-const hash = await bcrypt.hash(password, 10) // ✅
-const isValid = await bcrypt.compare(password, hash) // ✅
-
-// Don't use:
-const hash = bcrypt.hashSync(password, 10) // ❌ (blocks)
+ updateAge: 60 * 60 * 24, // Update session every 24 hours
+ },
+});
```
-**Alternative**: Use better-auth's built-in hashing (already optimized).
-
---
-### Issue 8: Social Provider Scope Issues
+### Issue 10: Social Provider Missing User Data
**Problem**: Social sign-in succeeds but missing user data (name, avatar).
**Symptoms**: `session.user.name` is null after Google/GitHub sign-in.
**Solution**: Request additional scopes:
+
```typescript
socialProviders: {
google: {
- clientId: process.env.GOOGLE_CLIENT_ID!,
- clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
- scope: ['openid', 'email', 'profile'] // Include 'profile' for name/image
+ clientId: env.GOOGLE_CLIENT_ID,
+ clientSecret: env.GOOGLE_CLIENT_SECRET,
+ scope: ["openid", "email", "profile"], // Include 'profile' for name/image
},
github: {
- clientId: process.env.GITHUB_CLIENT_ID!,
- clientSecret: process.env.GITHUB_CLIENT_SECRET!,
- scope: ['user:email', 'read:user'] // 'read:user' for full profile
- }
+ clientId: env.GITHUB_CLIENT_ID,
+ clientSecret: env.GITHUB_CLIENT_SECRET,
+ scope: ["user:email", "read:user"], // 'read:user' for full profile
+ },
}
```
---
-### Issue 9: Multi-Tenant Data Leakage
+### Issue 11: TypeScript Errors with Drizzle Schema
-**Problem**: Users see data from other tenants.
+**Problem**: TypeScript complains about schema types.
-**Symptoms**: User in Org A sees Org B's data.
+**Symptoms**: `Type 'DrizzleD1Database' is not assignable to...`
-**Solution**: Always filter queries by tenant ID:
-```typescript
-import { multiTenant } from 'better-auth/plugins'
+**Solution**: Export proper types from database:
-export const auth = betterAuth({
- database: /* ... */,
- plugins: [
- multiTenant({
- tenantIdHeader: 'x-tenant-id',
- isolateData: true // Enforces tenant isolation
- })
- ]
-})
-
-// In API routes
-app.get('/api/data', async (c) => {
- const session = await auth.getSession(c.req.raw)
- const tenantId = c.req.header('x-tenant-id')
+```typescript
+// src/db/index.ts
+import { drizzle, type DrizzleD1Database } from "drizzle-orm/d1";
+import * as schema from "./schema";
- // ALWAYS filter by tenant
- const data = await db.query.items.findMany({
- where: eq(items.tenantId, tenantId)
- })
+export type Database = DrizzleD1Database<typeof schema>;
- return c.json(data)
-})
+export function createDatabase(d1: D1Database): Database {
+ return drizzle(d1, { schema });
+}
```
---
-### Issue 10: Rate Limit False Positives
+### Issue 12: Wrangler Dev Mode Not Working
-**Problem**: Legitimate users blocked by rate limiting.
+**Problem**: `wrangler dev` fails with database errors.
-**Symptoms**: "Too many requests" errors for normal usage.
+**Symptoms**: "Database not found" or migration errors in local dev.
-**Solution**: Use IP + user ID for rate limit keys:
-```typescript
-import { rateLimit } from 'better-auth/plugins'
-
-plugins: [
- rateLimit({
- window: 60,
- max: 10,
- keyGenerator: (req) => {
- // Combine IP and user ID (if authenticated)
- const ip = req.headers.get('cf-connecting-ip') || 'unknown'
- const userId = req.session?.userId || 'anonymous'
- return `${ip}:${userId}`
- }
- })
-]
+**Solution**: Apply migrations locally first:
+
+```bash
+# Apply migrations to local D1
+wrangler d1 migrations apply my-app-db --local
+
+# Then run dev server
+wrangler dev
```
---
## Comparison: better-auth vs Alternatives
-| Feature | better-auth | Clerk | Auth.js |
-|---------|-------------|-------|---------|
-| **Hosting** | Self-hosted | Third-party | Self-hosted |
-| **Cost** | Free (OSS) | $25/mo+ | Free (OSS) |
-| **Cloudflare D1** | ✅ First-class | ❌ No | ✅ Adapter |
-| **Social Auth** | ✅ 10+ providers | ✅ Many | ✅ Many |
-| **2FA/Passkeys** | ✅ Plugin | ✅ Built-in | ⚠️ Limited |
-| **Organizations** | ✅ Plugin | ✅ Built-in | ❌ No |
-| **Multi-tenant** | ✅ Plugin | ✅ Yes | ❌ No |
-| **RBAC** | ✅ Plugin | ✅ Yes | ⚠️ Custom |
-| **Magic Links** | ✅ Built-in | ✅ Yes | ✅ Yes |
-| **Email/Password** | ✅ Built-in | ✅ Yes | ✅ Yes |
-| **Session Management** | ✅ JWT + DB | ✅ JWT | ✅ JWT + DB |
-| **TypeScript** | ✅ First-class | ✅ Yes | ✅ Yes |
-| **Framework Support** | ✅ Agnostic | ⚠️ React-focused | ✅ Agnostic |
-| **Vendor Lock-in** | ✅ None | ❌ High | ✅ None |
-| **Customization** | ✅ Full control | ⚠️ Limited | ✅ Full control |
-| **Production Ready** | ✅ Yes | ✅ Yes | ✅ Yes |
+| Feature | better-auth | Clerk | Auth.js |
+| -------------------- | ---------------- | --------------- | --------------- |
+| **Hosting** | Self-hosted | Third-party | Self-hosted |
+| **Cost** | Free (OSS) | $25/mo+ | Free (OSS) |
+| **Cloudflare D1** | ✅ Drizzle/Kysely | ❌ No | ✅ Adapter |
+| **Social Auth** | ✅ 10+ providers | ✅ Many | ✅ Many |
+| **2FA/Passkeys** | ✅ Plugin | ✅ Built-in | ⚠️ Limited |
+| **Organizations** | ✅ Plugin | ✅ Built-in | ❌ No |
+| **Multi-tenant** | ✅ Plugin | ✅ Yes | ❌ No |
+| **RBAC** | ✅ Plugin | ✅ Yes | ⚠️ Custom |
+| **Magic Links** | ✅ Built-in | ✅ Yes | ✅ Yes |
+| **Email/Password** | ✅ Built-in | ✅ Yes | ✅ Yes |
+| **Session Mgmt** | ✅ JWT + DB | ✅ JWT | ✅ JWT + DB |
+| **TypeScript** | ✅ First-class | ✅ Yes | ✅ Yes |
+| **Framework Support**| ✅ Agnostic | ⚠️ React-focused| ✅ Agnostic |
+| **Vendor Lock-in** | ✅ None | ❌ High | ✅ None |
+| **Customization** | ✅ Full control | ⚠️ Limited | ✅ Full control |
+| **Production Ready** | ✅ Yes | ✅ Yes | ✅ Yes |
**Recommendation**:
- **Use better-auth if**: Self-hosted, Cloudflare D1, want full control, avoid vendor lock-in
@@ -1090,6 +1046,90 @@ plugins: [
---
+## Migration Guides
+
+### From Clerk
+
+**Key differences**:
+- Clerk: Third-party service → better-auth: Self-hosted
+- Clerk: Proprietary → better-auth: Open source
+- Clerk: Monthly cost → better-auth: Free
+
+**Migration steps**:
+
+1. **Export user data** from Clerk (CSV or API)
+2. **Import into better-auth database**:
+ ```typescript
+ // migration script
+ const clerkUsers = await fetchClerkUsers();
+
+ for (const clerkUser of clerkUsers) {
+ await db.insert(user).values({
+ id: clerkUser.id,
+ email: clerkUser.email,
+ emailVerified: clerkUser.email_verified,
+ name: clerkUser.first_name + " " + clerkUser.last_name,
+ image: clerkUser.profile_image_url,
+ });
+ }
+ ```
+3. **Replace Clerk SDK** with better-auth client:
+ ```typescript
+ // Before (Clerk)
+ import { useUser } from "@clerk/nextjs";
+ const { user } = useUser();
+
+ // After (better-auth)
+ import { authClient } from "@/lib/auth-client";
+ const { data: session } = authClient.useSession();
+ const user = session?.user;
+ ```
+4. **Update middleware** for session verification
+5. **Configure social providers** (same OAuth apps, different config)
+
+---
+
+### From Auth.js (NextAuth)
+
+**Key differences**:
+- Auth.js: Limited features → better-auth: Comprehensive (2FA, orgs, etc.)
+- Auth.js: Callbacks-heavy → better-auth: Plugin-based
+- Auth.js: Session handling varies → better-auth: Consistent
+
+**Migration steps**:
+
+1. **Database schema**: Auth.js and better-auth use similar schemas, but column names differ
+2. **Replace configuration**:
+ ```typescript
+ // Before (Auth.js)
+ import NextAuth from "next-auth";
+ import GoogleProvider from "next-auth/providers/google";
+
+ export default NextAuth({
+ providers: [GoogleProvider({ /* ... */ })],
+ });
+
+ // After (better-auth)
+ import { betterAuth } from "better-auth";
+
+ export const auth = betterAuth({
+ socialProviders: {
+ google: { /* ... */ },
+ },
+ });
+ ```
+3. **Update client hooks**:
+ ```typescript
+ // Before
+ import { useSession } from "next-auth/react";
+
+ // After
+ import { authClient } from "@/lib/auth-client";
+ const { data: session } = authClient.useSession();
+ ```
+
+---
+
## Best Practices
### Security
@@ -1097,10 +1137,7 @@ plugins: [
1. **Always use HTTPS** in production (no exceptions)
2. **Rotate secrets** regularly:
```bash
- # Generate new secret
openssl rand -base64 32
-
- # Update in Wrangler
wrangler secret put BETTER_AUTH_SECRET
```
3. **Validate email domains** for sign-up:
@@ -1108,75 +1145,45 @@ plugins: [
emailAndPassword: {
enabled: true,
validate: async (email) => {
- const blockedDomains = ['tempmail.com', 'guerrillamail.com']
- const domain = email.split('@')[1]
+ const blockedDomains = ["tempmail.com", "guerrillamail.com"];
+ const domain = email.split("@")[1];
if (blockedDomains.includes(domain)) {
- throw new Error('Email domain not allowed')
+ throw new Error("Email domain not allowed");
}
- }
- }
- ```
-4. **Enable CSRF protection** (enabled by default in better-auth)
-5. **Use rate limiting** for auth endpoints
-6. **Log auth events** for security monitoring:
- ```typescript
- onSuccess: async (user, action) => {
- await logAuthEvent({
- userId: user.id,
- action, // 'sign-in', 'sign-up', 'password-change'
- timestamp: new Date(),
- ipAddress: req.headers.get('cf-connecting-ip')
- })
- }
+ },
+ };
```
+4. **Enable rate limiting** for auth endpoints
+5. **Log auth events** for security monitoring
---
### Performance
-1. **Cache session lookups** (use KV for Workers):
- ```typescript
- const session = await env.SESSIONS_KV.get(sessionId)
- if (session) return JSON.parse(session)
-
- // Fallback to DB if not in cache
- const dbSession = await db.query.sessions.findFirst(/* ... */)
- await env.SESSIONS_KV.put(sessionId, JSON.stringify(dbSession))
- ```
-
+1. **Cache session lookups** (use KV for Workers)
2. **Use indexes** on frequently queried fields:
```sql
- CREATE INDEX idx_sessions_user_id ON sessions(userId);
- CREATE INDEX idx_accounts_provider ON accounts(provider, providerAccountId);
+ CREATE INDEX idx_sessions_user_id ON session(userId);
+ CREATE INDEX idx_accounts_provider ON account(providerId, accountId);
```
-
3. **Minimize session data** (only essential fields)
-4. **Use CDN** for auth endpoints (cache public routes):
- ```typescript
- // Cache GET /api/auth/session for 5 minutes
- c.header('Cache-Control', 'public, max-age=300')
- ```
-
---
### Development Workflow
1. **Use environment-specific configs**:
```typescript
- const isDev = process.env.NODE_ENV === 'development'
+ const isDev = process.env.NODE_ENV === "development";
export const auth = betterAuth({
- database: /* ... */,
- baseURL: isDev
- ? 'http://localhost:3000'
- : 'https://yourdomain.com',
+ baseURL: isDev ? "http://localhost:3000" : "https://yourdomain.com",
session: {
expiresIn: isDev
? 60 * 60 * 24 * 365 // 1 year for dev
- : 60 * 60 * 24 * 7 // 7 days for prod
- }
- })
+ : 60 * 60 * 24 * 7, // 7 days for prod
+ },
+ });
```
2. **Test social auth locally** with ngrok:
@@ -1185,31 +1192,18 @@ plugins: [
# Use ngrok URL as redirect URI in OAuth provider
```
-3. **Seed test users** for development:
- ```typescript
- // seed.ts
- const testUsers = [
- { email: '[email protected]', password: 'password123', role: 'admin' },
- { email: '[email protected]', password: 'password123', role: 'user' }
- ]
-
- for (const user of testUsers) {
- await authClient.signUp.email(user)
- }
- ```
-
---
## Bundled Resources
This skill includes the following reference implementations:
-1. **`scripts/setup-d1.sh`** - Automated D1 database setup for Cloudflare Workers
-2. **`references/cloudflare-worker-example.ts`** - Complete Worker with auth + protected routes
-3. **`references/nextjs-api-route.ts`** - Next.js API route pattern
-4. **`references/react-client-hooks.tsx`** - React components with auth hooks
-5. **`references/drizzle-schema.ts`** - Drizzle ORM schema for better-auth tables
-6. **`assets/auth-flow-diagram.md`** - Visual flow diagrams for OAuth, email verification
+1. **`scripts/setup-d1-drizzle.sh`** - Complete D1 + Drizzle setup automation
+2. **`references/cloudflare-worker-drizzle.ts`** - Complete Worker with Drizzle auth
+3. **`references/cloudflare-worker-kysely.ts`** - Complete Worker with Kysely auth
+4. **`references/database-schema.ts`** - Complete better-auth Drizzle schema
+5. **`references/react-client-hooks.tsx`** - React components with auth hooks
+6. **`assets/auth-flow-diagram.md`** - Visual flow diagrams
Use `Read` tool to access these files when needed.
@@ -1217,21 +1211,35 @@ Use `Read` tool to access these files when needed.
## Token Efficiency
-**Without this skill**: ~15,000 tokens (setup trial-and-error, debugging CORS, D1 adapter, OAuth flows)
-**With this skill**: ~4,500 tokens (direct implementation from patterns)
-**Savings**: ~70% (10,500 tokens)
+**Without this skill**: ~20,000 tokens (setup trial-and-error, debugging D1 adapter, schema generation, CORS, OAuth)
+**With this skill**: ~6,000 tokens (direct implementation from correct patterns)
+**Savings**: ~70% (14,000 tokens)
-**Errors prevented**: 10 common issues documented with solutions
+**Errors prevented**: 12 common issues documented with solutions
---
## Additional Resources
- **Official Docs**: https://better-auth.com
-- **GitHub**: https://github.com/better-auth/better-auth
+- **GitHub**: https://github.com/better-auth/better-auth (22.4k ⭐)
- **Examples**: https://github.com/better-auth/better-auth/tree/main/examples
+- **Drizzle Docs**: https://orm.drizzle.team/docs/get-started-sqlite
+- **Kysely Docs**: https://kysely.dev/
- **Discord**: https://discord.gg/better-auth
-- **Migration Guides**: https://better-auth.com/docs/migrations
+
+---
+
+## Production Examples
+
+**Verified working repositories** (all use Drizzle or Kysely):
+
+1. **zwily/example-react-router-cloudflare-d1-drizzle-better-auth** - Drizzle
+2. **matthewlynch/better-auth-react-router-cloudflare-d1** - Kysely
+3. **foxlau/react-router-v7-better-auth** - Drizzle
+4. **zpg6/better-auth-cloudflare** - Drizzle (includes CLI)
+
+**None** use a direct `d1Adapter` - all require Drizzle/Kysely.
---
@@ -1239,8 +1247,11 @@ Use `Read` tool to access these files when needed.
**Tested with**:
+- `@noxharmonium/[email protected]`
- `@cloudflare/workers-types@latest`
- Node.js 18+, Bun 1.0+
@@ -1248,4 +1259,4 @@ Use `Read` tool to access these files when needed.
---
-**Last verified**: 2025-10-31 | **Skill version**: 1.0.0
+**Last verified**: 2025-11-08 | **Skill version**: 2.0.0 | **Breaking change**: Corrected D1 adapter patterns
diff --git a/skills/better-auth/references/cloudflare-worker-drizzle.ts b/skills/better-auth/references/cloudflare-worker-drizzle.ts
new file mode 100644
index 00000000..dfef5a69
--- /dev/null
+++ b/skills/better-auth/references/cloudflare-worker-drizzle.ts
@@ -0,0 +1,334 @@
+/**
+ * Complete Cloudflare Worker with better-auth + Drizzle ORM
+ *
+ * This example demonstrates:
+ * - D1 database with Drizzle ORM adapter
+ * - Email/password authentication
+ * - Google and GitHub OAuth
+ * - Protected routes with session verification
+ * - CORS configuration for SPA
+ * - KV storage for sessions (strong consistency)
+ * - Rate limiting with KV
+ *
+ * ⚠️ CRITICAL: better-auth requires Drizzle ORM or Kysely for D1
+ * There is NO direct d1Adapter()!
+ */
+
+import { Hono } from "hono";
+import { cors } from "hono/cors";
+import { betterAuth } from "better-auth";
+import { drizzleAdapter } from "better-auth/adapters/drizzle";
+import { drizzle, type DrizzleD1Database } from "drizzle-orm/d1";
+import { rateLimit } from "better-auth/plugins";
+import * as schema from "../db/schema"; // Your Drizzle schema
+
+// ═══════════════════════════════════════════════════════════════
+// Environment bindings
+// ═══════════════════════════════════════════════════════════════
+type Env = {
+ DB: D1Database;
+ SESSIONS_KV: KVNamespace;
+ RATE_LIMIT_KV: KVNamespace;
+ BETTER_AUTH_SECRET: string;
+ BETTER_AUTH_URL: string;
+ GOOGLE_CLIENT_ID: string;
+ GOOGLE_CLIENT_SECRET: string;
+ GITHUB_CLIENT_ID: string;
+ GITHUB_CLIENT_SECRET: string;
+ FRONTEND_URL: string;
+};
+
+// Database type
+export type Database = DrizzleD1Database<typeof schema>;
+
+const app = new Hono<{ Bindings: Env }>();
+
+// ═══════════════════════════════════════════════════════════════
+// CORS configuration for SPA
+// ═══════════════════════════════════════════════════════════════
+app.use("/api/*", async (c, next) => {
+ const corsMiddleware = cors({
+ origin: [c.env.FRONTEND_URL, "http://localhost:3000"],
+ credentials: true,
+ allowMethods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
+ allowHeaders: ["Content-Type", "Authorization"],
+ });
+ return corsMiddleware(c, next);
+});
+
+// ═══════════════════════════════════════════════════════════════
+// Helper: Initialize Drizzle database
+// ═══════════════════════════════════════════════════════════════
+function createDatabase(d1: D1Database): Database {
+ return drizzle(d1, { schema });
+}
+
+// ═══════════════════════════════════════════════════════════════
+// Helper: Initialize auth (per-request to access env)
+// ═══════════════════════════════════════════════════════════════
+function createAuth(db: Database, env: Env) {
+ return betterAuth({
+ // Base URL for OAuth callbacks
+ baseURL: env.BETTER_AUTH_URL,
+
+ // Secret for signing tokens
+ secret: env.BETTER_AUTH_SECRET,
+
+ // ⚠️ CRITICAL: Use Drizzle adapter with SQLite provider
+ // There is NO direct d1Adapter()!
+ database: drizzleAdapter(db, {
+ provider: "sqlite",
+ }),
+
+ // Email/password authentication
+ emailAndPassword: {
+ enabled: true,
+ requireEmailVerification: true,
+ sendVerificationEmail: async ({ user, url, token }) => {
+ // TODO: Implement email sending
+ // Use Resend, SendGrid, or Cloudflare Email Routing
+ console.log(`Verification email for ${user.email}: ${url}`);
+ console.log(`Verification code: ${token}`);
+ },
+ },
+
+ // Social providers
+ 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"],
+ },
+ },
+
+ // Session configuration
+ session: {
+ expiresIn: 60 * 60 * 24 * 7, // 7 days
+ updateAge: 60 * 60 * 24, // Update every 24 hours
+
+ // Use KV for sessions (strong consistency vs D1 eventual consistency)
+ storage: {
+ get: async (sessionId) => {
+ const session = await env.SESSIONS_KV.get(sessionId);
+ return session ? JSON.parse(session) : null;
+ },
+ set: async (sessionId, session, ttl) => {
+ await env.SESSIONS_KV.put(sessionId, JSON.stringify(session), {
+ expirationTtl: ttl,
+ });
+ },
+ delete: async (sessionId) => {
+ await env.SESSIONS_KV.delete(sessionId);
+ },
+ },
+ },
+
+ // Plugins
+ plugins: [
+ rateLimit({
+ window: 60, // 60 seconds
+ max: 10, // 10 requests per window
+ storage: {
+ get: async (key) => {
+ return await env.RATE_LIMIT_KV.get(key);
+ },
+ set: async (key, value, ttl) => {
+ await env.RATE_LIMIT_KV.put(key, value, {
+ expirationTtl: ttl,
+ });
+ },
+ },
+ }),
+ ],
+ });
+}
+
+// ═══════════════════════════════════════════════════════════════
+// Auth routes - handle all better-auth endpoints
+// ═══════════════════════════════════════════════════════════════
+app.all("/api/auth/*", async (c) => {
+ const db = createDatabase(c.env.DB);
+ const auth = createAuth(db, c.env);
+ return auth.handler(c.req.raw);
+});
+
+// ═══════════════════════════════════════════════════════════════
+// Example: Protected API route
+// ═══════════════════════════════════════════════════════════════
+app.get("/api/protected", async (c) => {
+ const db = createDatabase(c.env.DB);
+ const auth = createAuth(db, c.env);
+
+ // Verify session
+ const session = await auth.api.getSession({
+ headers: c.req.raw.headers,
+ });
+
+ if (!session) {
+ return c.json({ error: "Unauthorized" }, 401);
+ }
+
+ return c.json({
+ message: "Protected data",
+ user: {
+ id: session.user.id,
+ email: session.user.email,
+ name: session.user.name,
+ },
+ });
+});
+
+// ═══════════════════════════════════════════════════════════════
+// Example: User profile endpoint
+// ═══════════════════════════════════════════════════════════════
+app.get("/api/user/profile", async (c) => {
+ const db = createDatabase(c.env.DB);
+ const auth = createAuth(db, c.env);
+
+ const session = await auth.api.getSession({
+ headers: c.req.raw.headers,
+ });
+
+ if (!session) {
+ return c.json({ error: "Unauthorized" }, 401);
+ }
+
+ // Fetch additional user data from D1
+ const userProfile = await db.query.user.findFirst({
+ where: (user, { eq }) => eq(user.id, session.user.id),
+ });
+
+ return c.json(userProfile);
+});
+
+// ═══════════════════════════════════════════════════════════════
+// Example: Update user profile
+// ═══════════════════════════════════════════════════════════════
+app.patch("/api/user/profile", async (c) => {
+ const db = createDatabase(c.env.DB);
+ const auth = createAuth(db, c.env);
+
+ const session = await auth.api.getSession({
+ headers: c.req.raw.headers,
+ });
+
+ if (!session) {
+ return c.json({ error: "Unauthorized" }, 401);
+ }
+
+ const { name } = await c.req.json();
+
+ // Update user in D1 using Drizzle
+ await db
+ .update(schema.user)
+ .set({ name, updatedAt: new Date() })
+ .where(eq(schema.user.id, session.user.id));
+
+ return c.json({ success: true });
+});
+
+// ═══════════════════════════════════════════════════════════════
+// Example: Admin-only endpoint
+// ═══════════════════════════════════════════════════════════════
+app.get("/api/admin/users", async (c) => {
+ const db = createDatabase(c.env.DB);
+ const auth = createAuth(db, c.env);
+
+ const session = await auth.api.getSession({
+ headers: c.req.raw.headers,
+ });
+
+ if (!session) {
+ return c.json({ error: "Unauthorized" }, 401);
+ }
+
+ // Check admin role (you'd store this in users table)
+ const user = await db.query.user.findFirst({
+ where: (user, { eq }) => eq(user.id, session.user.id),
+ // Add role field to your schema if needed
+ });
+
+ // if (user.role !== 'admin') {
+ // return c.json({ error: 'Forbidden' }, 403)
+ // }
+
+ // Fetch all users
+ const users = await db.query.user.findMany({
+ columns: {
+ id: true,
+ email: true,
+ name: true,
+ createdAt: true,
+ },
+ });
+
+ return c.json(users);
+});
+
+// ═══════════════════════════════════════════════════════════════
+// Health check
+// ═══════════════════════════════════════════════════════════════
+app.get("/health", (c) => {
+ return c.json({
+ status: "ok",
+ timestamp: new Date().toISOString(),
+ });
+});
+
+// ═══════════════════════════════════════════════════════════════
+// Export Worker
+// ═══════════════════════════════════════════════════════════════
+export default app;
+
+/**
+ * ═══════════════════════════════════════════════════════════════
+ * SETUP CHECKLIST
+ * ═══════════════════════════════════════════════════════════════
+ *
+ * 1. Create D1 database:
+ * wrangler d1 create my-app-db
+ *
+ * 2. Create KV namespaces:
+ * wrangler kv:namespace create SESSIONS_KV
+ * wrangler kv:namespace create RATE_LIMIT_KV
+ *
+ * 3. Add to wrangler.toml:
+ * [[d1_databases]]
+ * binding = "DB"
+ * database_name = "my-app-db"
+ * database_id = "YOUR_ID"
+ *
+ * [[kv_namespaces]]
+ * binding = "SESSIONS_KV"
+ * id = "YOUR_ID"
+ *
+ * [[kv_namespaces]]
+ * binding = "RATE_LIMIT_KV"
+ * id = "YOUR_ID"
+ *
+ * [vars]
+ * BETTER_AUTH_URL = "http://localhost:8787"
+ * FRONTEND_URL = "http://localhost:3000"
+ *
+ * 4. Set secrets:
+ * 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
+ *
+ * 5. Generate and apply migrations:
+ * npx drizzle-kit generate
+ * wrangler d1 migrations apply my-app-db --local
+ * wrangler d1 migrations apply my-app-db --remote
+ *
+ * 6. Deploy:
+ * wrangler deploy
+ *
+ * ═══════════════════════════════════════════════════════════════
+ */
diff --git a/skills/better-auth/references/cloudflare-worker-kysely.ts b/skills/better-auth/references/cloudflare-worker-kysely.ts
new file mode 100644
index 00000000..07a6dc4e
--- /dev/null
+++ b/skills/better-auth/references/cloudflare-worker-kysely.ts
@@ -0,0 +1,240 @@
+/**
+ * Complete Cloudflare Worker with better-auth + Kysely
+ *
+ * This example demonstrates:
+ * - D1 database with Kysely adapter
+ * - Email/password authentication
+ * - Google OAuth
+ * - Protected routes with session verification
+ * - CORS configuration for SPA
+ * - CamelCasePlugin for schema conversion
+ *
+ * ⚠️ CRITICAL: better-auth requires Kysely (or Drizzle) for D1
+ * There is NO direct d1Adapter()!
+ */
+
+import { Hono } from "hono";
+import { cors } from "hono/cors";
+import { betterAuth } from "better-auth";
+import { Kysely, CamelCasePlugin } from "kysely";
+import { D1Dialect } from "@noxharmonium/kysely-d1";
+
+// ═══════════════════════════════════════════════════════════════
+// Environment bindings
+// ═══════════════════════════════════════════════════════════════
+type Env = {
+ DB: D1Database;
+ BETTER_AUTH_SECRET: string;
+ BETTER_AUTH_URL: string;
+ GOOGLE_CLIENT_ID: string;
+ GOOGLE_CLIENT_SECRET: string;
+ FRONTEND_URL: string;
+};
+
+const app = new Hono<{ Bindings: Env }>();
+
+// ═══════════════════════════════════════════════════════════════
+// CORS configuration for SPA
+// ═══════════════════════════════════════════════════════════════
+app.use("/api/*", async (c, next) => {
+ const corsMiddleware = cors({
+ origin: [c.env.FRONTEND_URL, "http://localhost:3000"],
+ credentials: true,
+ allowMethods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
+ allowHeaders: ["Content-Type", "Authorization"],
+ });
+ return corsMiddleware(c, next);
+});
+
+// ═══════════════════════════════════════════════════════════════
+// Helper: Initialize auth with Kysely
+// ═══════════════════════════════════════════════════════════════
+function createAuth(env: Env) {
+ return betterAuth({
+ // Base URL for OAuth callbacks
+ baseURL: env.BETTER_AUTH_URL,
+
+ // Secret for signing tokens
+ secret: env.BETTER_AUTH_SECRET,
+
+ // ⚠️ CRITICAL: Use Kysely with D1Dialect
+ // There is NO direct d1Adapter()!
+ database: {
+ db: new Kysely({
+ dialect: new D1Dialect({
+ database: env.DB,
+ }),
+ plugins: [
+ // CRITICAL: CamelCasePlugin converts between snake_case (DB) and camelCase (better-auth)
+ // Without this, session reads will fail if your schema uses snake_case
+ new CamelCasePlugin(),
+ ],
+ }),
+ type: "sqlite",
+ },
+
+ // Email/password authentication
+ emailAndPassword: {
+ enabled: true,
+ requireEmailVerification: true,
+ sendVerificationEmail: async ({ user, url, token }) => {
+ // TODO: Implement email sending
+ console.log(`Verification email for ${user.email}: ${url}`);
+ console.log(`Verification code: ${token}`);
+ },
+ },
+
+ // Social providers
+ socialProviders: {
+ google: {
+ clientId: env.GOOGLE_CLIENT_ID,
+ clientSecret: env.GOOGLE_CLIENT_SECRET,
+ scope: ["openid", "email", "profile"],
+ },
+ },
+
+ // Session configuration
+ session: {
+ expiresIn: 60 * 60 * 24 * 7, // 7 days
+ updateAge: 60 * 60 * 24, // Update every 24 hours
+ },
+ });
+}
+
+// ═══════════════════════════════════════════════════════════════
+// Auth routes - handle all better-auth endpoints
+// ═══════════════════════════════════════════════════════════════
+app.all("/api/auth/*", async (c) => {
+ const auth = createAuth(c.env);
+ return auth.handler(c.req.raw);
+});
+
+// ═══════════════════════════════════════════════════════════════
+// Example: Protected API route
+// ═══════════════════════════════════════════════════════════════
+app.get("/api/protected", async (c) => {
+ const auth = createAuth(c.env);
+
+ // Verify session
+ const session = await auth.api.getSession({
+ headers: c.req.raw.headers,
+ });
+
+ if (!session) {
+ return c.json({ error: "Unauthorized" }, 401);
+ }
+
+ return c.json({
+ message: "Protected data",
+ user: {
+ id: session.user.id,
+ email: session.user.email,
+ name: session.user.name,
+ },
+ });
+});
+
+// ═══════════════════════════════════════════════════════════════
+// Example: User profile endpoint
+// ═══════════════════════════════════════════════════════════════
+app.get("/api/user/profile", async (c) => {
+ const auth = createAuth(c.env);
+
+ const session = await auth.api.getSession({
+ headers: c.req.raw.headers,
+ });
+
+ if (!session) {
+ return c.json({ error: "Unauthorized" }, 401);
+ }
+
+ // Fetch user data using Kysely
+ const db = new Kysely({
+ dialect: new D1Dialect({ database: c.env.DB }),
+ plugins: [new CamelCasePlugin()],
+ });
+
+ const user = await db
+ .selectFrom("user")
+ .select(["id", "email", "name", "image", "createdAt"])
+ .where("id", "=", session.user.id)
+ .executeTakeFirst();
+
+ return c.json(user);
+});
+
+// ═══════════════════════════════════════════════════════════════
+// Health check
+// ═══════════════════════════════════════════════════════════════
+app.get("/health", (c) => {
+ return c.json({
+ status: "ok",
+ timestamp: new Date().toISOString(),
+ });
+});
+
+// ═══════════════════════════════════════════════════════════════
+// Export Worker
+// ═══════════════════════════════════════════════════════════════
+export default app;
+
+/**
+ * ═══════════════════════════════════════════════════════════════
+ * SETUP CHECKLIST
+ * ═══════════════════════════════════════════════════════════════
+ *
+ * 1. Install dependencies:
+ * npm install better-auth kysely @noxharmonium/kysely-d1 hono
+ *
+ * 2. Create D1 database:
+ * wrangler d1 create my-app-db
+ *
+ * 3. Add to wrangler.toml:
+ * [[d1_databases]]
+ * binding = "DB"
+ * database_name = "my-app-db"
+ * database_id = "YOUR_ID"
+ *
+ * [vars]
+ * BETTER_AUTH_URL = "http://localhost:8787"
+ * FRONTEND_URL = "http://localhost:3000"
+ *
+ * 4. Set secrets:
+ * wrangler secret put BETTER_AUTH_SECRET
+ * wrangler secret put GOOGLE_CLIENT_ID
+ * wrangler secret put GOOGLE_CLIENT_SECRET
+ *
+ * 5. Create database schema manually (Kysely doesn't auto-generate):
+ * wrangler d1 execute my-app-db --local --command "
+ * CREATE TABLE user (
+ * id TEXT PRIMARY KEY,
+ * name TEXT NOT NULL,
+ * email TEXT NOT NULL UNIQUE,
+ * email_verified INTEGER NOT NULL DEFAULT 0,
+ * image TEXT,
+ * created_at INTEGER NOT NULL DEFAULT (unixepoch()),
+ * updated_at INTEGER NOT NULL DEFAULT (unixepoch())
+ * );
+ * CREATE TABLE session (...);
+ * CREATE TABLE account (...);
+ * CREATE TABLE verification (...);
+ * "
+ *
+ * 6. Apply schema to remote:
+ * wrangler d1 execute my-app-db --remote --file schema.sql
+ *
+ * 7. Deploy:
+ * wrangler deploy
+ *
+ * ═══════════════════════════════════════════════════════════════
+ * WHY CamelCasePlugin?
+ * ═══════════════════════════════════════════════════════════════
+ *
+ * If your database schema uses snake_case (email_verified),
+ * but better-auth expects camelCase (emailVerified), the
+ * CamelCasePlugin automatically converts between the two.
+ *
+ * Without it, session reads will fail with missing fields.
+ *
+ * ═══════════════════════════════════════════════════════════════
+ */
diff --git a/skills/better-auth/references/database-schema.ts b/skills/better-auth/references/database-schema.ts
new file mode 100644
index 00000000..fe7f9533
--- /dev/null
+++ b/skills/better-auth/references/database-schema.ts
@@ -0,0 +1,315 @@
+/**
+ * Complete better-auth Database Schema for Drizzle ORM + D1
+ *
+ * This schema includes all tables required by better-auth core.
+ * You can add your own application tables below.
+ *
+ * ═══════════════════════════════════════════════════════════════
+ * CRITICAL NOTES
+ * ═══════════════════════════════════════════════════════════════
+ *
+ * 1. Column names use camelCase (emailVerified, createdAt)
+ * - This matches better-auth expectations
+ * - If you use snake_case, you MUST use CamelCasePlugin with Kysely
+ *
+ * 2. Timestamps use INTEGER with mode: "timestamp"
+ * - D1 (SQLite) doesn't have native timestamp type
+ * - Unix epoch timestamps (seconds since 1970)
+ *
+ * 3. Booleans use INTEGER with mode: "boolean"
+ * - D1 (SQLite) doesn't have native boolean type
+ * - 0 = false, 1 = true
+ *
+ * 4. Foreign keys use onDelete: "cascade"
+ * - Automatically delete related records
+ * - session deleted when user deleted
+ * - account deleted when user deleted
+ *
+ * ═══════════════════════════════════════════════════════════════
+ */
+
+import { integer, sqliteTable, text, index } from "drizzle-orm/sqlite-core";
+import { sql } from "drizzle-orm";
+
+// ═══════════════════════════════════════════════════════════════
+// better-auth CORE TABLES
+// ═══════════════════════════════════════════════════════════════
+
+/**
+ * Users table - stores all user accounts
+ */
+export const user = sqliteTable(
+ "user",
+ {
+ id: text().primaryKey(),
+ name: text().notNull(),
+ email: text().notNull().unique(),
+ emailVerified: integer({ mode: "boolean" }).notNull().default(false),
+ image: text(), // Profile picture URL
+ createdAt: integer({ mode: "timestamp" })
+ .notNull()
+ .default(sql`(unixepoch())`),
+ updatedAt: integer({ mode: "timestamp" })
+ .notNull()
+ .default(sql`(unixepoch())`),
+ },
+ (table) => ({
+ emailIdx: index("user_email_idx").on(table.email),
+ })
+);
+
+/**
+ * Sessions table - stores active user sessions
+ *
+ * NOTE: Consider using KV storage for sessions instead of D1
+ * to avoid eventual consistency issues
+ */
+export const session = sqliteTable(
+ "session",
+ {
+ id: text().primaryKey(),
+ userId: text()
+ .notNull()
+ .references(() => user.id, { onDelete: "cascade" }),
+ token: text().notNull().unique(),
+ expiresAt: integer({ mode: "timestamp" }).notNull(),
+ ipAddress: text(),
+ userAgent: text(),
+ createdAt: integer({ mode: "timestamp" })
+ .notNull()
+ .default(sql`(unixepoch())`),
+ updatedAt: integer({ mode: "timestamp" })
+ .notNull()
+ .default(sql`(unixepoch())`),
+ },
+ (table) => ({
+ userIdIdx: index("session_user_id_idx").on(table.userId),
+ tokenIdx: index("session_token_idx").on(table.token),
+ })
+);
+
+/**
+ * Accounts table - stores OAuth provider accounts and passwords
+ */
+export const account = sqliteTable(
+ "account",
+ {
+ id: text().primaryKey(),
+ userId: text()
+ .notNull()
+ .references(() => user.id, { onDelete: "cascade" }),
+ accountId: text().notNull(), // Provider's user ID
+ providerId: text().notNull(), // "google", "github", etc.
+ accessToken: text(),
+ refreshToken: text(),
+ accessTokenExpiresAt: integer({ mode: "timestamp" }),
+ refreshTokenExpiresAt: integer({ mode: "timestamp" }),
+ scope: text(), // OAuth scopes granted
+ idToken: text(), // OpenID Connect ID token
+ password: text(), // Hashed password for email/password auth
+ createdAt: integer({ mode: "timestamp" })
+ .notNull()
+ .default(sql`(unixepoch())`),
+ updatedAt: integer({ mode: "timestamp" })
+ .notNull()
+ .default(sql`(unixepoch())`),
+ },
+ (table) => ({
+ userIdIdx: index("account_user_id_idx").on(table.userId),
+ providerIdx: index("account_provider_idx").on(
+ table.providerId,
+ table.accountId
+ ),
+ })
+);
+
+/**
+ * Verification tokens - for email verification, password reset, etc.
+ */
+export const verification = sqliteTable(
+ "verification",
+ {
+ id: text().primaryKey(),
+ identifier: text().notNull(), // Email or user ID
+ value: text().notNull(), // Token value
+ expiresAt: integer({ mode: "timestamp" }).notNull(),
+ createdAt: integer({ mode: "timestamp" })
+ .notNull()
+ .default(sql`(unixepoch())`),
+ updatedAt: integer({ mode: "timestamp" })
+ .notNull()
+ .default(sql`(unixepoch())`),
+ },
+ (table) => ({
+ identifierIdx: index("verification_identifier_idx").on(table.identifier),
+ valueIdx: index("verification_value_idx").on(table.value),
+ })
+);
+
+// ═══════════════════════════════════════════════════════════════
+// OPTIONAL: Additional tables for better-auth plugins
+// ═══════════════════════════════════════════════════════════════
+
+/**
+ * Two-Factor Authentication table (if using 2FA plugin)
+ */
+export const twoFactor = sqliteTable(
+ "two_factor",
+ {
+ id: text().primaryKey(),
+ userId: text()
+ .notNull()
+ .references(() => user.id, { onDelete: "cascade" }),
+ secret: text().notNull(), // TOTP secret
+ backupCodes: text(), // JSON array of backup codes
+ enabled: integer({ mode: "boolean" }).notNull().default(false),
+ createdAt: integer({ mode: "timestamp" })
+ .notNull()
+ .default(sql`(unixepoch())`),
+ },
+ (table) => ({
+ userIdIdx: index("two_factor_user_id_idx").on(table.userId),
+ })
+);
+
+/**
+ * Organizations table (if using organization plugin)
+ */
+export const organization = sqliteTable("organization", {
+ id: text().primaryKey(),
+ name: text().notNull(),
+ slug: text().notNull().unique(),
+ logo: text(),
+ createdAt: integer({ mode: "timestamp" })
+ .notNull()
+ .default(sql`(unixepoch())`),
+ updatedAt: integer({ mode: "timestamp" })
+ .notNull()
+ .default(sql`(unixepoch())`),
+});
+
+/**
+ * Organization members table (if using organization plugin)
+ */
+export const organizationMember = sqliteTable(
+ "organization_member",
+ {
+ id: text().primaryKey(),
+ organizationId: text()
+ .notNull()
+ .references(() => organization.id, { onDelete: "cascade" }),
+ userId: text()
+ .notNull()
+ .references(() => user.id, { onDelete: "cascade" }),
+ role: text().notNull(), // "owner", "admin", "member"
+ createdAt: integer({ mode: "timestamp" })
+ .notNull()
+ .default(sql`(unixepoch())`),
+ },
+ (table) => ({
+ orgIdIdx: index("org_member_org_id_idx").on(table.organizationId),
+ userIdIdx: index("org_member_user_id_idx").on(table.userId),
+ })
+);
+
+// ═══════════════════════════════════════════════════════════════
+// YOUR APPLICATION TABLES
+// ═══════════════════════════════════════════════════════════════
+
+/**
+ * Example: User profile extension
+ */
+export const profile = sqliteTable("profile", {
+ id: text().primaryKey(),
+ userId: text()
+ .notNull()
+ .references(() => user.id, { onDelete: "cascade" }),
+ bio: text(),
+ website: text(),
+ location: text(),
+ phone: text(),
+ createdAt: integer({ mode: "timestamp" })
+ .notNull()
+ .default(sql`(unixepoch())`),
+ updatedAt: integer({ mode: "timestamp" })
+ .notNull()
+ .default(sql`(unixepoch())`),
+});
+
+/**
+ * Example: User preferences
+ */
+export const userPreferences = sqliteTable("user_preferences", {
+ id: text().primaryKey(),
+ userId: text()
+ .notNull()
+ .references(() => user.id, { onDelete: "cascade" }),
+ theme: text().notNull().default("system"), // "light", "dark", "system"
+ language: text().notNull().default("en"),
+ emailNotifications: integer({ mode: "boolean" }).notNull().default(true),
+ pushNotifications: integer({ mode: "boolean" }).notNull().default(false),
+ createdAt: integer({ mode: "timestamp" })
+ .notNull()
+ .default(sql`(unixepoch())`),
+ updatedAt: integer({ mode: "timestamp" })
+ .notNull()
+ .default(sql`(unixepoch())`),
+});
+
+// ═══════════════════════════════════════════════════════════════
+// Export all schemas for Drizzle
+// ═══════════════════════════════════════════════════════════════
+export const schema = {
+ user,
+ session,
+ account,
+ verification,
+ twoFactor,
+ organization,
+ organizationMember,
+ profile,
+ userPreferences,
+} as const;
+
+/**
+ * ═══════════════════════════════════════════════════════════════
+ * USAGE INSTRUCTIONS
+ * ═══════════════════════════════════════════════════════════════
+ *
+ * 1. Save this file as: src/db/schema.ts
+ *
+ * 2. Create drizzle.config.ts:
+ * import type { Config } from "drizzle-kit";
+ *
+ * export default {
+ * out: "./drizzle",
+ * schema: "./src/db/schema.ts",
+ * dialect: "sqlite",
+ * driver: "d1-http",
+ * dbCredentials: {
+ * databaseId: process.env.CLOUDFLARE_DATABASE_ID!,
+ * accountId: process.env.CLOUDFLARE_ACCOUNT_ID!,
+ * token: process.env.CLOUDFLARE_TOKEN!,
+ * },
+ * } satisfies Config;
+ *
+ * 3. Generate migrations:
+ * npx drizzle-kit generate
+ *
+ * 4. Apply migrations to D1:
+ * wrangler d1 migrations apply my-app-db --local
+ * wrangler d1 migrations apply my-app-db --remote
+ *
+ * 5. Use in your Worker:
+ * import { drizzle } from "drizzle-orm/d1";
+ * import * as schema from "./db/schema";
+ *
+ * const db = drizzle(env.DB, { schema });
+ *
+ * 6. Query example:
+ * const users = await db.query.user.findMany({
+ * where: (user, { eq }) => eq(user.emailVerified, true)
+ * });
+ *
+ * ═══════════════════════════════════════════════════════════════
+ */
diff --git a/skills/better-auth/scripts/setup-d1-drizzle.sh b/skills/better-auth/scripts/setup-d1-drizzle.sh
new file mode 100644
index 00000000..7b09428b
--- /dev/null
+++ b/skills/better-auth/scripts/setup-d1-drizzle.sh
@@ -0,0 +1,221 @@
+#!/bin/bash
+
+# ═══════════════════════════════════════════════════════════════
+# better-auth + D1 + Drizzle ORM Setup Script
+# ═══════════════════════════════════════════════════════════════
+#
+# This script automates the setup of better-auth with Cloudflare D1
+# and Drizzle ORM.
+#
+# CRITICAL: better-auth requires Drizzle ORM or Kysely for D1.
+# There is NO direct d1Adapter()!
+#
+# Usage:
+# chmod +x setup-d1-drizzle.sh
+# ./setup-d1-drizzle.sh my-app-name
+#
+# ═══════════════════════════════════════════════════════════════
+
+set -e # Exit on error
+
+# Colors for output
+RED='\033[0;31m'
+GREEN='\033[0;32m'
+YELLOW='\033[1;33m'
+BLUE='\033[0;34m'
+NC='\033[0m' # No Color
+
+# Check if app name provided
+if [ -z "$1" ]; then
+ echo -e "${RED}Error: Please provide an app name${NC}"
+ echo "Usage: ./setup-d1-drizzle.sh my-app-name"
+ exit 1
+fi
+
+APP_NAME=$1
+DB_NAME="${APP_NAME}-db"
+
+echo -e "${BLUE}═══════════════════════════════════════════════════════════════${NC}"
+echo -e "${BLUE}better-auth + D1 + Drizzle Setup${NC}"
+echo -e "${BLUE}═══════════════════════════════════════════════════════════════${NC}"
+echo ""
+echo -e "App Name: ${GREEN}$APP_NAME${NC}"
+echo -e "Database: ${GREEN}$DB_NAME${NC}"
+echo ""
+
+# ═══════════════════════════════════════════════════════════════
+# Step 1: Install dependencies
+# ═══════════════════════════════════════════════════════════════
+echo -e "${YELLOW}[1/8]${NC} Installing dependencies..."
+npm install better-auth drizzle-orm drizzle-kit @cloudflare/workers-types hono
+
+# ═══════════════════════════════════════════════════════════════
+# Step 2: Create D1 database
+# ═══════════════════════════════════════════════════════════════
+echo -e "${YELLOW}[2/8]${NC} Creating D1 database..."
+wrangler d1 create $DB_NAME
+
+echo -e "${GREEN}✓${NC} Database created!"
+echo -e "${YELLOW}⚠${NC} Copy the database_id from the output above and update wrangler.toml"
+echo ""
+read -p "Press Enter after updating wrangler.toml..."
+
+# ═══════════════════════════════════════════════════════════════
+# Step 3: Create directory structure
+# ═══════════════════════════════════════════════════════════════
+echo -e "${YELLOW}[3/8]${NC} Creating directory structure..."
+mkdir -p src/db
+mkdir -p drizzle
+
+# ═══════════════════════════════════════════════════════════════
+# Step 4: Create database schema
+# ═══════════════════════════════════════════════════════════════
+echo -e "${YELLOW}[4/8]${NC} Creating database schema..."
+cat > src/db/schema.ts << 'EOF'
+import { integer, sqliteTable, text } from "drizzle-orm/sqlite-core";
+import { sql } from "drizzle-orm";
+
+export const user = sqliteTable("user", {
+ id: text().primaryKey(),
+ name: text().notNull(),
+ email: text().notNull().unique(),
+ emailVerified: integer({ mode: "boolean" }).notNull().default(false),
+ image: text(),
+ createdAt: integer({ mode: "timestamp" })
+ .notNull()
+ .default(sql`(unixepoch())`),
+ updatedAt: integer({ mode: "timestamp" })
+ .notNull()
+ .default(sql`(unixepoch())`),
+});
+
+export const session = sqliteTable("session", {
+ id: text().primaryKey(),
+ userId: text()
+ .notNull()
+ .references(() => user.id, { onDelete: "cascade" }),
+ token: text().notNull(),
+ expiresAt: integer({ mode: "timestamp" }).notNull(),
+ ipAddress: text(),
+ userAgent: text(),
+ createdAt: integer({ mode: "timestamp" })
+ .notNull()
+ .default(sql`(unixepoch())`),
+ updatedAt: integer({ mode: "timestamp" })
+ .notNull()
+ .default(sql`(unixepoch())`),
+});
+
+export const account = sqliteTable("account", {
+ id: text().primaryKey(),
+ userId: text()
+ .notNull()
+ .references(() => user.id, { onDelete: "cascade" }),
+ accountId: text().notNull(),
+ providerId: text().notNull(),
+ accessToken: text(),
+ refreshToken: text(),
+ accessTokenExpiresAt: integer({ mode: "timestamp" }),
+ refreshTokenExpiresAt: integer({ mode: "timestamp" }),
+ scope: text(),
+ idToken: text(),
+ password: text(),
+ createdAt: integer({ mode: "timestamp" })
+ .notNull()
+ .default(sql`(unixepoch())`),
+ updatedAt: integer({ mode: "timestamp" })
+ .notNull()
+ .default(sql`(unixepoch())`),
+});
+
+export const verification = sqliteTable("verification", {
+ id: text().primaryKey(),
+ identifier: text().notNull(),
+ value: text().notNull(),
+ expiresAt: integer({ mode: "timestamp" }).notNull(),
+ createdAt: integer({ mode: "timestamp" })
+ .notNull()
+ .default(sql`(unixepoch())`),
+ updatedAt: integer({ mode: "timestamp" })
+ .notNull()
+ .default(sql`(unixepoch())`),
+});
+EOF
+
+# ═══════════════════════════════════════════════════════════════
+# Step 5: Create Drizzle config
+# ═══════════════════════════════════════════════════════════════
+echo -e "${YELLOW}[5/8]${NC} Creating Drizzle config..."
+cat > drizzle.config.ts << 'EOF'
+import type { Config } from "drizzle-kit";
+
+export default {
+ out: "./drizzle",
+ schema: "./src/db/schema.ts",
+ dialect: "sqlite",
+ driver: "d1-http",
+ dbCredentials: {
+ databaseId: process.env.CLOUDFLARE_DATABASE_ID!,
+ accountId: process.env.CLOUDFLARE_ACCOUNT_ID!,
+ token: process.env.CLOUDFLARE_TOKEN!,
+ },
+} satisfies Config;
+EOF
+
+echo -e "${GREEN}✓${NC} Config created"
+echo ""
+echo -e "${YELLOW}⚠${NC} Create a .env file with:"
+echo " CLOUDFLARE_ACCOUNT_ID=your-account-id"
+echo " CLOUDFLARE_DATABASE_ID=your-database-id"
+echo " CLOUDFLARE_TOKEN=your-api-token"
+echo ""
+read -p "Press Enter after creating .env..."
+
+# ═══════════════════════════════════════════════════════════════
+# Step 6: Generate migrations
+# ═══════════════════════════════════════════════════════════════
+echo -e "${YELLOW}[6/8]${NC} Generating migrations..."
+npx drizzle-kit generate
+
+# ═══════════════════════════════════════════════════════════════
+# Step 7: Apply migrations
+# ═══════════════════════════════════════════════════════════════
+echo -e "${YELLOW}[7/8]${NC} Applying migrations..."
+echo -e "Applying to ${GREEN}local${NC} D1..."
+wrangler d1 migrations apply $DB_NAME --local
+
+read -p "Apply to remote D1 too? (y/n) " -n 1 -r
+echo
+if [[ $REPLY =~ ^[Yy]$ ]]; then
+ echo -e "Applying to ${GREEN}remote${NC} D1..."
+ wrangler d1 migrations apply $DB_NAME --remote
+fi
+
+# ═══════════════════════════════════════════════════════════════
+# Step 8: Set secrets
+# ═══════════════════════════════════════════════════════════════
+echo -e "${YELLOW}[8/8]${NC} Setting secrets..."
+echo ""
+echo -e "${BLUE}Generating BETTER_AUTH_SECRET...${NC}"
+SECRET=$(openssl rand -base64 32)
+echo "$SECRET" | wrangler secret put BETTER_AUTH_SECRET
+
+echo ""
+echo -e "${GREEN}✓ Setup complete!${NC}"
+echo ""
+echo -e "${BLUE}═══════════════════════════════════════════════════════════════${NC}"
+echo -e "${BLUE}Next Steps${NC}"
+echo -e "${BLUE}═══════════════════════════════════════════════════════════════${NC}"
+echo ""
+echo "1. Add OAuth client IDs and secrets (if needed):"
+echo " wrangler secret put GOOGLE_CLIENT_ID"
+echo " wrangler secret put GOOGLE_CLIENT_SECRET"
+echo ""
+echo "2. Test locally:"
+echo " npm run dev"
+echo ""
+echo "3. Deploy:"
+echo " wrangler deploy"
+echo ""
+echo -e "${YELLOW}⚠ IMPORTANT:${NC} Update your wrangler.toml with the database_id from Step 2"
+echo ""