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 cleanup - Remove legacy files with incorrect D1 patterns

Jez3f47f4c74f88
diff --git a/skills/better-auth/references/cloudflare-worker-example.ts b/skills/better-auth/references/cloudflare-worker-example.ts
deleted file mode 100644
index 50f1d67a..00000000
--- a/skills/better-auth/references/cloudflare-worker-example.ts
+++ /dev/null
@@ -1,220 +0,0 @@
-/**
- * Complete Cloudflare Worker with better-auth
- *
- * This example demonstrates:
- * - D1 database adapter
- * - Email/password authentication
- * - Google OAuth
- * - Protected routes with session verification
- * - CORS configuration for SPA
- * - KV storage for sessions (strong consistency)
- * - Rate limiting
- */
-
-import { Hono } from 'hono'
-import { cors } from 'hono/cors'
-import { betterAuth } from 'better-auth'
-import { d1Adapter } from 'better-auth/adapters/d1'
-import { rateLimit } from 'better-auth/plugins'
-
-// Environment bindings
-type Env = {
- DB: D1Database
- SESSIONS_KV: KVNamespace
- RATE_LIMIT_KV: KVNamespace
- BETTER_AUTH_SECRET: string
- GOOGLE_CLIENT_ID: string
- GOOGLE_CLIENT_SECRET: string
- GITHUB_CLIENT_ID: string
- GITHUB_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 (per-request to access env)
-function initAuth(env: Env) {
- return betterAuth({
- // D1 adapter for user data
- database: d1Adapter(env.DB),
-
- // Secret for signing tokens
- secret: env.BETTER_AUTH_SECRET,
-
- // Base URL for callbacks
- baseURL: env.FRONTEND_URL,
-
- // Email/password authentication
- emailAndPassword: {
- enabled: true,
- requireEmailVerification: true,
- sendVerificationEmail: async ({ user, url, token }) => {
- // TODO: Implement email sending
- // Example: Use Resend, SendGrid, or Cloudflare Email Routing
- console.log(`Verification email for ${user.email}: ${url}`)
- }
- },
-
- // 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 auth = initAuth(c.env)
- return auth.handler(c.req.raw)
-})
-
-// Example: Protected API route
-app.get('/api/protected', async (c) => {
- const auth = initAuth(c.env)
- const session = await auth.getSession(c.req.raw)
-
- 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 = initAuth(c.env)
- const session = await auth.getSession(c.req.raw)
-
- if (!session) {
- return c.json({ error: 'Unauthorized' }, 401)
- }
-
- // Fetch additional user data from D1
- const userProfile = await c.env.DB
- .prepare('SELECT * FROM users WHERE id = ?')
- .bind(session.user.id)
- .first()
-
- return c.json(userProfile)
-})
-
-// Example: Update user profile
-app.patch('/api/user/profile', async (c) => {
- const auth = initAuth(c.env)
- const session = await auth.getSession(c.req.raw)
-
- if (!session) {
- return c.json({ error: 'Unauthorized' }, 401)
- }
-
- const { name, bio } = await c.req.json()
-
- // Update user in D1
- await c.env.DB
- .prepare('UPDATE users SET name = ?, bio = ?, updatedAt = ? WHERE id = ?')
- .bind(name, bio, Date.now(), session.user.id)
- .run()
-
- return c.json({ success: true })
-})
-
-// Example: Admin-only endpoint
-app.get('/api/admin/users', async (c) => {
- const auth = initAuth(c.env)
- const session = await auth.getSession(c.req.raw)
-
- if (!session) {
- return c.json({ error: 'Unauthorized' }, 401)
- }
-
- // Check admin role (you'd store this in users table)
- const user = await c.env.DB
- .prepare('SELECT role FROM users WHERE id = ?')
- .bind(session.user.id)
- .first()
-
- if (user.role !== 'admin') {
- return c.json({ error: 'Forbidden' }, 403)
- }
-
- // Fetch all users
- const users = await c.env.DB
- .prepare('SELECT id, email, name, role, createdAt FROM users')
- .all()
-
- return c.json(users.results)
-})
-
-// Health check
-app.get('/health', (c) => {
- return c.json({ status: 'ok' })
-})
-
-export default app
diff --git a/skills/better-auth/references/drizzle-schema.ts b/skills/better-auth/references/drizzle-schema.ts
deleted file mode 100644
index b2f79392..00000000
--- a/skills/better-auth/references/drizzle-schema.ts
+++ /dev/null
@@ -1,175 +0,0 @@
-/**
- * Drizzle ORM Schema for better-auth
- *
- * This schema includes all tables needed by better-auth core
- * and common plugins (organizations, 2FA, etc.)
- *
- * Use with PostgreSQL or Cloudflare D1
- */
-
-import { sqliteTable, text, integer } from 'drizzle-orm/sqlite-core' // For D1
-// OR for PostgreSQL:
-// import { pgTable, text, timestamp, boolean, json } from 'drizzle-orm/pg-core'
-
-// ============================================================================
-// Core better-auth Tables
-// ============================================================================
-
-// Users table
-export const users = sqliteTable('users', {
- id: text('id').primaryKey(),
- email: text('email').unique().notNull(),
- emailVerified: integer('email_verified', { mode: 'boolean' }).default(false),
- name: text('name'),
- image: text('image'),
- role: text('role').default('user'), // Custom field for RBAC
- bio: text('bio'), // Custom field
- createdAt: integer('created_at', { mode: 'timestamp' }).notNull(),
- updatedAt: integer('updated_at', { mode: 'timestamp' }).notNull()
-})
-
-// Sessions table
-export const sessions = sqliteTable('sessions', {
- id: text('id').primaryKey(),
- userId: text('user_id').notNull().references(() => users.id, { onDelete: 'cascade' }),
- expiresAt: integer('expires_at', { mode: 'timestamp' }).notNull(),
- ipAddress: text('ip_address'),
- userAgent: text('user_agent'),
- createdAt: integer('created_at', { mode: 'timestamp' }).notNull()
-})
-
-// Accounts table (for OAuth providers)
-export const accounts = sqliteTable('accounts', {
- id: text('id').primaryKey(),
- userId: text('user_id').notNull().references(() => users.id, { onDelete: 'cascade' }),
- provider: text('provider').notNull(), // 'google', 'github', etc.
- providerAccountId: text('provider_account_id').notNull(),
- accessToken: text('access_token'),
- refreshToken: text('refresh_token'),
- expiresAt: integer('expires_at', { mode: 'timestamp' }),
- tokenType: text('token_type'),
- scope: text('scope'),
- idToken: text('id_token'),
- createdAt: integer('created_at', { mode: 'timestamp' }).notNull(),
- updatedAt: integer('updated_at', { mode: 'timestamp' }).notNull()
-})
-
-// Verification tokens (for email verification, password reset)
-export const verificationTokens = sqliteTable('verification_tokens', {
- identifier: text('identifier').notNull(), // email or user ID
- token: text('token').notNull(),
- expires: integer('expires', { mode: 'timestamp' }).notNull(),
- createdAt: integer('created_at', { mode: 'timestamp' }).notNull()
-})
-
-// ============================================================================
-// Organizations Plugin Tables
-// ============================================================================
-
-export const organizations = sqliteTable('organizations', {
- id: text('id').primaryKey(),
- name: text('name').notNull(),
- slug: text('slug').unique().notNull(),
- logo: text('logo'),
- createdAt: integer('created_at', { mode: 'timestamp' }).notNull(),
- updatedAt: integer('updated_at', { mode: 'timestamp' }).notNull()
-})
-
-export const organizationMembers = sqliteTable('organization_members', {
- id: text('id').primaryKey(),
- organizationId: text('organization_id').notNull().references(() => organizations.id, { onDelete: 'cascade' }),
- userId: text('user_id').notNull().references(() => users.id, { onDelete: 'cascade' }),
- role: text('role').notNull(), // 'owner', 'admin', 'member'
- createdAt: integer('created_at', { mode: 'timestamp' }).notNull()
-})
-
-export const organizationInvitations = sqliteTable('organization_invitations', {
- id: text('id').primaryKey(),
- organizationId: text('organization_id').notNull().references(() => organizations.id, { onDelete: 'cascade' }),
- email: text('email').notNull(),
- role: text('role').notNull(),
- invitedBy: text('invited_by').notNull().references(() => users.id),
- token: text('token').notNull(),
- expiresAt: integer('expires_at', { mode: 'timestamp' }).notNull(),
- createdAt: integer('created_at', { mode: 'timestamp' }).notNull()
-})
-
-// ============================================================================
-// Two-Factor Authentication Plugin Tables
-// ============================================================================
-
-export const twoFactorSecrets = sqliteTable('two_factor_secrets', {
- id: text('id').primaryKey(),
- userId: text('user_id').notNull().references(() => users.id, { onDelete: 'cascade' }),
- secret: text('secret').notNull(),
- method: text('method').notNull(), // 'totp', 'sms'
- enabled: integer('enabled', { mode: 'boolean' }).default(false),
- createdAt: integer('created_at', { mode: 'timestamp' }).notNull()
-})
-
-export const twoFactorBackupCodes = sqliteTable('two_factor_backup_codes', {
- id: text('id').primaryKey(),
- userId: text('user_id').notNull().references(() => users.id, { onDelete: 'cascade' }),
- code: text('code').notNull(),
- used: integer('used', { mode: 'boolean' }).default(false),
- createdAt: integer('created_at', { mode: 'timestamp' }).notNull()
-})
-
-// ============================================================================
-// Custom Application Tables (Examples)
-// ============================================================================
-
-// Example: User preferences
-export const userPreferences = sqliteTable('user_preferences', {
- id: text('id').primaryKey(),
- userId: text('user_id').notNull().references(() => users.id, { onDelete: 'cascade' }),
- theme: text('theme').default('system'), // 'light', 'dark', 'system'
- language: text('language').default('en'),
- notifications: integer('notifications', { mode: 'boolean' }).default(true),
- createdAt: integer('created_at', { mode: 'timestamp' }).notNull(),
- updatedAt: integer('updated_at', { mode: 'timestamp' }).notNull()
-})
-
-// Example: Audit log
-export const auditLogs = sqliteTable('audit_logs', {
- id: text('id').primaryKey(),
- userId: text('user_id').references(() => users.id, { onDelete: 'set null' }),
- action: text('action').notNull(), // 'login', 'logout', 'password_change', etc.
- resource: text('resource'), // 'user', 'organization', etc.
- resourceId: text('resource_id'),
- ipAddress: text('ip_address'),
- userAgent: text('user_agent'),
- metadata: text('metadata'), // JSON string
- createdAt: integer('created_at', { mode: 'timestamp' }).notNull()
-})
-
-// ============================================================================
-// PostgreSQL Version (Alternative to SQLite above)
-// ============================================================================
-
-/*
-import { pgTable, text, timestamp, boolean, json } 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'),
- role: text('role').default('user'),
- createdAt: timestamp('created_at').notNull().defaultNow(),
- updatedAt: timestamp('updated_at').notNull().defaultNow()
-})
-
-// ... similar structure for other tables
-*/
-
-// ============================================================================
-// Type Exports
-// ============================================================================
-
-export type User = typeof users.$inferSelect
-export type Session = typeof sessions.$inferSelect
-export type Account = typeof accounts.$inferSelect
-export type Organization = typeof organizations.$inferSelect
-export type OrganizationMember = typeof organizationMembers.$inferSelect
diff --git a/skills/better-auth/references/nextjs/README.md b/skills/better-auth/references/nextjs/README.md
new file mode 100644
index 00000000..d98227ab
--- /dev/null
+++ b/skills/better-auth/references/nextjs/README.md
@@ -0,0 +1,41 @@
+# Next.js Examples
+
+This directory contains better-auth examples for **Next.js with PostgreSQL**.
+
+**Important**: These examples are NOT for Cloudflare D1. They use PostgreSQL via Hyperdrive or direct connection.
+
+## Files
+
+### `postgres-example.ts`
+Complete Next.js API route with better-auth using:
+- **PostgreSQL** (not D1)
+- Drizzle ORM with `postgres` driver
+- Organizations plugin
+- 2FA plugin
+- Email verification
+- Custom error handling
+
+**Use this example when**:
+- Building Next.js application (not Cloudflare Workers)
+- Using PostgreSQL database
+- Need organizations and 2FA features
+
+**Installation**:
+```bash
+npm install better-auth drizzle-orm postgres
+```
+
+**Environment variables**:
+```env
+DATABASE_URL=postgresql://user:password@host:5432/database
+BETTER_AUTH_SECRET=your-secret
+NEXT_PUBLIC_APP_URL=http://localhost:3000
+GOOGLE_CLIENT_ID=your-google-client-id
+GOOGLE_CLIENT_SECRET=your-google-client-secret
+```
+
+---
+
+**For Cloudflare D1 examples**, see the parent `references/` directory:
+- `cloudflare-worker-drizzle.ts` - Complete Worker with Drizzle + D1
+- `cloudflare-worker-kysely.ts` - Complete Worker with Kysely + D1
diff --git a/skills/better-auth/references/nextjs-api-route.ts b/skills/better-auth/references/nextjs/postgres-example.ts
similarity index 100%
rename from skills/better-auth/references/nextjs-api-route.ts
rename to skills/better-auth/references/nextjs/postgres-example.ts
diff --git a/skills/better-auth/references/react-client-hooks.tsx b/skills/better-auth/references/react-client-hooks.tsx
index a090fcbf..70391b4f 100644
--- a/skills/better-auth/references/react-client-hooks.tsx
+++ b/skills/better-auth/references/react-client-hooks.tsx
@@ -12,9 +12,8 @@
'use client'
-import { createAuthClient } from 'better-auth/client'
-import { useSession } from 'better-auth/client'
-import { useState } from 'react'
+import { createAuthClient, useSession } from 'better-auth/client'
+import { useState, useEffect } from 'react'
// Initialize auth client
export const authClient = createAuthClient({
@@ -379,14 +378,14 @@ export function OrganizationSwitcher() {
const [loading, setLoading] = useState(true)
// Fetch user's organizations
- useState(() => {
+ useEffect(() => {
async function fetchOrgs() {
const orgs = await authClient.organization.listUserOrganizations()
setOrganizations(orgs)
setLoading(false)
}
fetchOrgs()
- })
+ }, [])
const switchOrganization = async (orgId: string) => {
await authClient.organization.setActiveOrganization({ organizationId: orgId })
diff --git a/skills/better-auth/scripts/setup-d1.sh b/skills/better-auth/scripts/setup-d1.sh
deleted file mode 100755
index 466ed75c..00000000
--- a/skills/better-auth/scripts/setup-d1.sh
+++ /dev/null
@@ -1,265 +0,0 @@
-#!/bin/bash
-# =============================================================================
-# Setup Cloudflare D1 Database for better-auth
-# =============================================================================
-#
-# This script automates the creation and migration of a D1 database for
-# better-auth authentication.
-#
-# Usage:
-# ./setup-d1.sh [database-name]
-#
-# Example:
-# ./setup-d1.sh my-app-db
-#
-# Prerequisites:
-# - Wrangler CLI installed (npm install -g wrangler)
-# - Authenticated with Cloudflare (wrangler login)
-# - better-auth installed (npm install better-auth)
-#
-# =============================================================================
-
-set -e # Exit on error
-
-# Colors for output
-RED='\033[0;31m'
-GREEN='\033[0;32m'
-YELLOW='\033[1;33m'
-NC='\033[0m' # No Color
-
-# Default database name
-DB_NAME="${1:-better-auth-db}"
-
-echo -e "${GREEN}========================================${NC}"
-echo -e "${GREEN}better-auth D1 Database Setup${NC}"
-echo -e "${GREEN}========================================${NC}"
-echo ""
-
-# Check if wrangler is installed
-if ! command -v wrangler &> /dev/null; then
- echo -e "${RED}❌ Error: wrangler CLI not found${NC}"
- echo "Install with: npm install -g wrangler"
- exit 1
-fi
-
-# Check if authenticated
-if ! wrangler whoami &> /dev/null; then
- echo -e "${YELLOW}⚠️ Not authenticated with Cloudflare${NC}"
- echo "Running: wrangler login"
- wrangler login
-fi
-
-echo -e "${GREEN}✅ Wrangler CLI ready${NC}"
-echo ""
-
-# Step 1: Create D1 database
-echo -e "${YELLOW}📦 Creating D1 database: ${DB_NAME}${NC}"
-DB_OUTPUT=$(wrangler d1 create "$DB_NAME" 2>&1 || true)
-
-if echo "$DB_OUTPUT" | grep -q "already exists"; then
- echo -e "${YELLOW}⚠️ Database ${DB_NAME} already exists, skipping creation${NC}"
- DB_ID=$(wrangler d1 list | grep "$DB_NAME" | awk '{print $2}')
-else
- echo "$DB_OUTPUT"
- DB_ID=$(echo "$DB_OUTPUT" | grep -oP 'database_id = "\K[^"]+' || echo "")
-fi
-
-if [ -z "$DB_ID" ]; then
- echo -e "${RED}❌ Failed to get database ID${NC}"
- exit 1
-fi
-
-echo -e "${GREEN}✅ Database created/found: ${DB_ID}${NC}"
-echo ""
-
-# Step 2: Generate SQL schema
-echo -e "${YELLOW}📝 Generating better-auth schema...${NC}"
-
-SCHEMA_FILE="migrations/0001_better_auth_initial.sql"
-mkdir -p migrations
-
-cat > "$SCHEMA_FILE" << 'EOF'
--- better-auth Core Tables
--- Generated for Cloudflare D1
-
--- Users table
-CREATE TABLE IF NOT EXISTS users (
- id TEXT PRIMARY KEY,
- email TEXT UNIQUE NOT NULL,
- email_verified INTEGER DEFAULT 0,
- name TEXT,
- image TEXT,
- role TEXT DEFAULT 'user',
- created_at INTEGER NOT NULL,
- updated_at INTEGER NOT NULL
-);
-
-CREATE INDEX IF NOT EXISTS idx_users_email ON users(email);
-
--- Sessions table
-CREATE TABLE IF NOT EXISTS sessions (
- id TEXT PRIMARY KEY,
- user_id TEXT NOT NULL,
- expires_at INTEGER NOT NULL,
- ip_address TEXT,
- user_agent TEXT,
- created_at INTEGER NOT NULL,
- FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
-);
-
-CREATE INDEX IF NOT EXISTS idx_sessions_user_id ON sessions(user_id);
-CREATE INDEX IF NOT EXISTS idx_sessions_expires_at ON sessions(expires_at);
-
--- Accounts table (OAuth providers)
-CREATE TABLE IF NOT EXISTS accounts (
- id TEXT PRIMARY KEY,
- user_id TEXT NOT NULL,
- provider TEXT NOT NULL,
- provider_account_id TEXT NOT NULL,
- access_token TEXT,
- refresh_token TEXT,
- expires_at INTEGER,
- token_type TEXT,
- scope TEXT,
- id_token TEXT,
- created_at INTEGER NOT NULL,
- updated_at INTEGER NOT NULL,
- FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
-);
-
-CREATE INDEX IF NOT EXISTS idx_accounts_user_id ON accounts(user_id);
-CREATE INDEX IF NOT EXISTS idx_accounts_provider ON accounts(provider, provider_account_id);
-
--- Verification tokens
-CREATE TABLE IF NOT EXISTS verification_tokens (
- identifier TEXT NOT NULL,
- token TEXT NOT NULL,
- expires INTEGER NOT NULL,
- created_at INTEGER NOT NULL,
- PRIMARY KEY (identifier, token)
-);
-
-CREATE INDEX IF NOT EXISTS idx_verification_tokens_expires ON verification_tokens(expires);
-
--- Optional: Organizations (if using organization plugin)
-CREATE TABLE IF NOT EXISTS organizations (
- id TEXT PRIMARY KEY,
- name TEXT NOT NULL,
- slug TEXT UNIQUE NOT NULL,
- logo TEXT,
- created_at INTEGER NOT NULL,
- updated_at INTEGER NOT NULL
-);
-
-CREATE TABLE IF NOT EXISTS organization_members (
- id TEXT PRIMARY KEY,
- organization_id TEXT NOT NULL,
- user_id TEXT NOT NULL,
- role TEXT NOT NULL,
- created_at INTEGER NOT NULL,
- FOREIGN KEY (organization_id) REFERENCES organizations(id) ON DELETE CASCADE,
- FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
-);
-
-CREATE INDEX IF NOT EXISTS idx_org_members_org_id ON organization_members(organization_id);
-CREATE INDEX IF NOT EXISTS idx_org_members_user_id ON organization_members(user_id);
-
-CREATE TABLE IF NOT EXISTS organization_invitations (
- id TEXT PRIMARY KEY,
- organization_id TEXT NOT NULL,
- email TEXT NOT NULL,
- role TEXT NOT NULL,
- invited_by TEXT NOT NULL,
- token TEXT NOT NULL,
- expires_at INTEGER NOT NULL,
- created_at INTEGER NOT NULL,
- FOREIGN KEY (organization_id) REFERENCES organizations(id) ON DELETE CASCADE,
- FOREIGN KEY (invited_by) REFERENCES users(id)
-);
-
-CREATE INDEX IF NOT EXISTS idx_org_invitations_token ON organization_invitations(token);
-
--- Optional: 2FA (if using twoFactor plugin)
-CREATE TABLE IF NOT EXISTS two_factor_secrets (
- id TEXT PRIMARY KEY,
- user_id TEXT NOT NULL,
- secret TEXT NOT NULL,
- method TEXT NOT NULL,
- enabled INTEGER DEFAULT 0,
- created_at INTEGER NOT NULL,
- FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
-);
-
-CREATE TABLE IF NOT EXISTS two_factor_backup_codes (
- id TEXT PRIMARY KEY,
- user_id TEXT NOT NULL,
- code TEXT NOT NULL,
- used INTEGER DEFAULT 0,
- created_at INTEGER NOT NULL,
- FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
-);
-EOF
-
-echo -e "${GREEN}✅ Schema generated: ${SCHEMA_FILE}${NC}"
-echo ""
-
-# Step 3: Apply migration to local D1
-echo -e "${YELLOW}🔧 Applying migration to local database...${NC}"
-wrangler d1 execute "$DB_NAME" --local --file="$SCHEMA_FILE"
-echo -e "${GREEN}✅ Local migration complete${NC}"
-echo ""
-
-# Step 4: Apply migration to remote D1
-read -p "Apply migration to remote (production) database? (y/N) " -n 1 -r
-echo
-if [[ $REPLY =~ ^[Yy]$ ]]; then
- echo -e "${YELLOW}🚀 Applying migration to remote database...${NC}"
- wrangler d1 execute "$DB_NAME" --remote --file="$SCHEMA_FILE"
- echo -e "${GREEN}✅ Remote migration complete${NC}"
-else
- echo -e "${YELLOW}⏭️ Skipped remote migration${NC}"
- echo "Run manually with: wrangler d1 execute $DB_NAME --remote --file=$SCHEMA_FILE"
-fi
-echo ""
-
-# Step 5: Update wrangler.toml
-echo -e "${YELLOW}📋 wrangler.toml configuration:${NC}"
-echo ""
-echo "Add this to your wrangler.toml:"
-echo ""
-echo "[[d1_databases]]"
-echo "binding = \"DB\""
-echo "database_name = \"$DB_NAME\""
-echo "database_id = \"$DB_ID\""
-echo ""
-
-# Step 6: Environment variables reminder
-echo -e "${YELLOW}🔑 Required secrets (set with wrangler secret put):${NC}"
-echo ""
-echo "wrangler secret put BETTER_AUTH_SECRET"
-echo "wrangler secret put GOOGLE_CLIENT_ID # If using Google OAuth"
-echo "wrangler secret put GOOGLE_CLIENT_SECRET # If using Google OAuth"
-echo "wrangler secret put GITHUB_CLIENT_ID # If using GitHub OAuth"
-echo "wrangler secret put GITHUB_CLIENT_SECRET # If using GitHub OAuth"
-echo ""
-
-# Step 7: Generate auth secret
-echo -e "${YELLOW}🔐 Generate auth secret:${NC}"
-AUTH_SECRET=$(openssl rand -base64 32 2>/dev/null || head -c 32 /dev/urandom | base64)
-echo "Use this secret (or generate your own):"
-echo "$AUTH_SECRET"
-echo ""
-echo "Set it with: echo \"$AUTH_SECRET\" | wrangler secret put BETTER_AUTH_SECRET"
-echo ""
-
-echo -e "${GREEN}========================================${NC}"
-echo -e "${GREEN}✅ Setup Complete!${NC}"
-echo -e "${GREEN}========================================${NC}"
-echo ""
-echo "Next steps:"
-echo "1. Update wrangler.toml with the D1 binding above"
-echo "2. Set secrets with: wrangler secret put BETTER_AUTH_SECRET"
-echo "3. Configure OAuth providers if needed"
-echo "4. Deploy with: wrangler deploy"
-echo ""
-echo "Need help? Check the better-auth skill documentation"