Skip to content

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

better-auth

Verified

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

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

references/cloudflare-worker-kysely.ts

View on GitHub
/**
 * 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 (Resend, SendGrid, or Cloudflare Email Routing).
        // Pass `url` to your email provider so the user can click through.
        // ❌ NEVER log `url` or `token` — both are single-use secrets, and
        //    wrangler tail / Logpush persist stdout. Redacted stub only:
        console.log(`Verification email sent to ${user.email.substring(0, 2)}***`);
      },
    },

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