better-auth - D1 Adapter & Error Prevention Guide

SkillCloud & infra

Build authentication systems for TypeScript/Cloudflare Workers with social auth, 2FA, passkeys, organizations, and RBAC. Self-hosted alternative to Clerk/Auth.js.

Available today. Use it from your connected AI after setup.

Connect ahel once, and every AI you use reads what you have installed.

Then ask your AI: use the better-auth - D1 Adapter & Error Prevention Guide skill

What this skill tells your AI

The instructions your AI receives, as published by ovachiever/droid-tings in skills/better-auth/SKILL.md and read by ahel’s review.

Package: better-auth@1.4.0 (Nov 22, 2025) Breaking Changes: ESM-only (v1.4.0), Multi-team table changes (v1.3), D1 requires Drizzle/Kysely (no direct adapter)


⚠️ CRITICAL: D1 Adapter Requirement

better-auth DOES NOT have d1Adapter(). You MUST use:

  • Drizzle ORM (recommended): drizzleAdapter(db, { provider: "sqlite" })
  • Kysely: new Kysely({ dialect: new D1Dialect({ database: env.DB }) })

See Issue #1 below for details.


What's New in v1.4.0 (Nov 22, 2025)

Major Features:

  • Stateless session management - Sessions without database storage
  • ESM-only package ⚠️ Breaking: CommonJS no longer supported
  • JWT key rotation - Automatic key rotation for enhanced security
  • SCIM provisioning - Enterprise user provisioning protocol
  • @standard-schema/spec - Replaces ZodType for validation
  • CaptchaFox integration - Built-in CAPTCHA support
  • Automatic server-side IP detection
  • Cookie-based account data storage
  • Multiple passkey origins support
  • RP-Initiated Logout endpoint (OIDC)

📚 Docs: https://www.better-auth.com/changelogs


What's New in v1.3 (July 2025)

Major Features:

  • SSO with SAML 2.0 - Enterprise single sign-on (moved to separate @better-auth/sso package)
  • Multi-team support ⚠️ Breaking: teamId removed from member table, new teamMembers table required
  • Additional fields - Custom fields for organization/member/invitation models
  • Performance improvements and bug fixes

📚 Docs: https://www.better-auth.com/blog/1-3


Alternative: Kysely Adapter Pattern

If you prefer Kysely over Drizzle:

File: src/auth.ts

import { betterAuth } from "better-auth";
import { Kysely, CamelCasePlugin } from "kysely";
import { D1Dialect } from "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.


Framework Integrations

TanStack Start

⚠️ CRITICAL: TanStack Start requires the reactStartCookies plugin to handle cookie setting properly.

import { betterAuth } from "better-auth";
import { drizzleAdapter } from "better-auth/adapters/drizzle";
import { reactStartCookies } from "better-auth/react-start";

export const auth = betterAuth({
  database: drizzleAdapter(db, { provider: "sqlite" }),
  plugins: [
    twoFactor(),
    organization(),
    reactStartCookies(), // ⚠️ MUST be LAST plugin
  ],
});

Why it's needed: TanStack Start uses a special cookie handling system. Without this plugin, auth functions like signInEmail() and signUpEmail() won't set cookies properly, causing authentication to fail.

Important: The reactStartCookies plugin must be the last plugin in the array.

API Route Setup (/src/routes/api/auth/$.ts):

import { auth } from '@/lib/auth'
import { createFileRoute } from '@tanstack/react-router'

export const Route = createFileRoute('/api/auth/$')({
  server: {
    handlers: {
      GET: ({ request }) => auth.handler(request),
      POST: ({ request }) => auth.handler(request),
    },
  },
})

📚 Official Docs: https://www.better-auth.com/docs/integrations/tanstack


Available Plugins (v1.3+)

Better Auth provides plugins for advanced authentication features:

PluginImportDescriptionDocs
OIDC Providerbetter-auth/pluginsBuild your own OpenID Connect provider (become an OAuth provider for other apps)📚
SSObetter-auth/pluginsEnterprise Single Sign-On with OIDC, OAuth2, and SAML 2.0 support📚
Stripebetter-auth/pluginsPayment and subscription management (stable as of v1.3+)📚
MCPbetter-auth/pluginsAct as OAuth provider for Model Context Protocol (MCP) clients📚
Expobetter-auth/expoReact Native/Expo integration with secure cookie management📚

API Reference

Overview: What You Get For Free

When you call auth.handler(), better-auth automatically exposes 80+ production-ready REST endpoints at /api/auth/*. Every endpoint is also available as a server-side method via auth.api.* for programmatic use.

This dual-layer API system means:

  • Clients (React, Vue, mobile apps) call HTTP endpoints directly
  • Server-side code (middleware, background jobs) uses auth.api.* methods
  • Zero boilerplate - no need to write auth endpoints manually

Time savings: Building this from scratch = ~220 hours. With better-auth = ~4-8 hours. 97% reduction.


Auto-Generated HTTP Endpoints

All endpoints are automatically exposed at /api/auth/* when using auth.handler().

Core Authentication Endpoints
EndpointMethodDescription
/sign-up/emailPOSTRegister with email/password
/sign-in/emailPOSTAuthenticate with email/password
/sign-outPOSTLogout user
/change-passwordPOSTUpdate password (requires current password)
/forget-passwordPOSTInitiate password reset flow
/reset-passwordPOSTComplete password reset with token
/send-verification-emailPOSTSend email verification link
/verify-emailGETVerify email with token (?token=<token>)
/get-sessionGETRetrieve current session
/list-sessionsGETGet all active user sessions
/revoke-sessionPOSTEnd specific session
/revoke-other-sessionsPOSTEnd all sessions except current
/revoke-sessionsPOSTEnd all user sessions
/update-userPOSTModify user profile (name, image)
/change-emailPOSTUpdate email address
/set-passwordPOSTAdd password to OAuth-only account
/delete-userPOSTRemove user account
/list-accountsGETGet linked authentication providers
/link-socialPOSTConnect OAuth provider to account
/unlink-accountPOSTDisconnect provider
Social OAuth Endpoints
EndpointMethodDescription
/sign-in/socialPOSTInitiate OAuth flow (provider specified in body)
/callback/:providerGETOAuth callback handler (e.g., /callback/google)
/get-access-tokenGETRetrieve provider access token

Example OAuth flow:

// Client initiates
await authClient.signIn.social({
  provider: "google",
  callbackURL: "/dashboard",
});

// better-auth handles redirect to Google
// Google redirects back to /api/auth/callback/google
// better-auth creates session automatically

Plugin Endpoints
Two-Factor Authentication (2FA Plugin)
import { twoFactor } from "better-auth/plugins";
EndpointMethodDescription
/two-factor/enablePOSTActivate 2FA for user
/two-factor/disablePOSTDeactivate 2FA
/two-factor/get-totp-uriGETGet QR code URI for authenticator app
/two-factor/verify-totpPOSTValidate TOTP code from authenticator
/two-factor/send-otpPOSTSend OTP via email
/two-factor/verify-otpPOSTValidate email OTP
/two-factor/generate-backup-codesPOSTCreate recovery codes
/two-factor/verify-backup-codePOSTUse backup code for login
/two-factor/view-backup-codesGETView current backup codes

📚 Docs: https://www.better-auth.com/docs/plugins/2fa

Organization Plugin (Multi-Tenant SaaS)
import { organization } from "better-auth/plugins";

Organizations (10 endpoints):

EndpointMethodDescription
/organization/createPOSTCreate organization
/organization/listGETList user's organizations
/organization/get-fullGETGet complete org details
/organization/updatePUTModify organization
/organization/deleteDELETERemove organization
/organization/check-slugGETVerify slug availability
/organization/set-activePOSTSet active organization context

Members (8 endpoints):

EndpointMethodDescription
/organization/list-membersGETGet organization members
/organization/add-memberPOSTAdd member directly
/organization/remove-memberDELETERemove member
/organization/update-member-rolePUTChange member role
/organization/get-active-memberGETGet current member info
/organization/leavePOSTLeave organization

Invitations (7 endpoints):

EndpointMethodDescription
/organization/invite-memberPOSTSend invitation email
/organization/accept-invitationPOSTAccept invite
/organization/reject-invitationPOSTReject invite
/organization/cancel-invitationPOSTCancel pending invite
/organization/get-invitationGETGet invitation details
/organization/list-invitationsGETList org invitations
/organization/list-user-invitationsGETList user's pending invites

Teams (8 endpoints):

EndpointMethodDescription
/organization/create-teamPOSTCreate team within org
/organization/list-teamsGETList organization teams
/organization/update-teamPUTModify team
/organization/remove-teamDELETERemove team
/organization/set-active-teamPOSTSet active team context
/organization/list-team-membersGETList team members
/organization/add-team-memberPOSTAdd member to team
/organization/remove-team-memberDELETERemove team member

Permissions & Roles (6 endpoints):

EndpointMethodDescription
/organization/has-permissionPOSTCheck if user has permission
/organization/create-rolePOSTCreate custom role
/organization/delete-roleDELETEDelete custom role
/organization/list-rolesGETList all roles
/organization/get-roleGETGet role details
/organization/update-rolePUTModify role permissions

📚 Docs: https://www.better-auth.com/docs/plugins/organization

Admin Plugin
import { admin } from "better-auth/plugins";
EndpointMethodDescription
/admin/create-userPOSTCreate user as admin
/admin/list-usersGETList all users (with filters/pagination)
/admin/set-rolePOSTAssign user role
/admin/set-user-passwordPOSTChange user password
/admin/update-userPUTModify user details
/admin/remove-userDELETEDelete user account
/admin/ban-userPOSTBan user account
/admin/unban-userPOSTUnban user
/admin/list-user-sessionsGETGet user's active sessions
/admin/revoke-user-sessionDELETEEnd specific user session
/admin/revoke-user-sessionsDELETEEnd all user sessions
/admin/impersonate-userPOSTStart impersonating user
/admin/stop-impersonatingPOSTEnd impersonation session

📚 Docs: https://www.better-auth.com/docs/plugins/admin

Other Plugin Endpoints

Passkey Plugin (5 endpoints) - Docs:

  • /passkey/add, /sign-in/passkey, /passkey/list, /passkey/delete, /passkey/update

Magic Link Plugin (2 endpoints) - Docs:

  • /sign-in/magic-link, /magic-link/verify

Username Plugin (2 endpoints) - Docs:

  • /sign-in/username, /username/is-available

Phone Number Plugin (5 endpoints) - Docs:

  • /sign-in/phone-number, /phone-number/send-otp, /phone-number/verify, /phone-number/request-password-reset, /phone-number/reset-password

Email OTP Plugin (6 endpoints) - Docs:

  • /email-otp/send-verification-otp, /email-otp/check-verification-otp, /sign-in/email-otp, /email-otp/verify-email, /forget-password/email-otp, /email-otp/reset-password

Anonymous Plugin (1 endpoint) - Docs:

  • /sign-in/anonymous

JWT Plugin (2 endpoints) - Docs:

  • /token (get JWT), /jwks (public key for verification)

OpenAPI Plugin (2 endpoints) - Docs:

  • /reference (interactive API docs with Scalar UI)
  • /generate-openapi-schema (get OpenAPI spec as JSON)

Server-Side API Methods (auth.api.*)

Every HTTP endpoint has a corresponding server-side method. Use these for:

  • Server-side middleware (protecting routes)
  • Background jobs (user cleanup, notifications)
  • Admin operations (bulk user management)
  • Custom auth flows (programmatic session creation)
Core API Methods
// Authentication
await auth.api.signUpEmail({
  body: { email, password, name },
  headers: request.headers,
});

await auth.api.signInEmail({
  body: { email, password, rememberMe: true },
  headers: request.headers,
});

await auth.api.signOut({ headers: request.headers });

// Session Management
const session = await auth.api.getSession({ headers: request.headers });

await auth.api.listSessions({ headers: request.headers });

await auth.api.revokeSession({
  body: { token: "session_token_here" },
  headers: request.headers,
});

// User Management
await auth.api.updateUser({
  body: { name: "New Name", image: "https://..." },
  headers: request.headers,
});

await auth.api.changeEmail({
  body: { newEmail: "newemail@example.com" },
  headers: request.headers,
});

await auth.api.deleteUser({
  body: { password: "current_password" },
  headers: request.headers,
});

// Account Linking
await auth.api.linkSocialAccount({
  body: { provider: "google" },
  headers: request.headers,
});

await auth.api.unlinkAccount({
  body: { providerId: "google", accountId: "google_123" },
  headers: request.headers,
});
Plugin API Methods

2FA Plugin:

// Enable 2FA
const { totpUri, backupCodes } = await auth.api.enableTwoFactor({
  body: { issuer: "MyApp" },
  headers: request.headers,
});

// Verify TOTP code
await auth.api.verifyTOTP({
  body: { code: "123456", trustDevice: true },
  headers: request.headers,
});

// Generate backup codes
const { backupCodes } = await auth.api.generateBackupCodes({
  headers: request.headers,
});

Organization Plugin:

// Create organization
const org = await auth.api.createOrganization({
  body: { name: "Acme Corp", slug: "acme" },
  headers: request.headers,
});

// Add member
await auth.api.addMember({
  body: {
    userId: "user_123",
    role: "admin",
    organizationId: org.id,
  },
  headers: request.headers,
});

// Check permissions
const hasPermission = await auth.api.hasPermission({
  body: {
    organizationId: org.id,
    permission: "users:delete",
  },
  headers: request.headers,
});

Admin Plugin:

// List users with pagination
const users = await auth.api.listUsers({
  query: {
    search: "john",
    limit: 10,
    offset: 0,
    sortBy: "createdAt",
    sortOrder: "desc",
  },
  headers: request.headers,
});

// Ban user
await auth.api.banUser({
  body: {
    userId: "user_123",
    reason: "Violation of ToS",
    expiresAt: new Date("2025-12-31"),
  },
  headers: request.headers,
});

// Impersonate user (for admin support)
const impersonationSession = await auth.api.impersonateUser({
  body: {
    userId: "user_123",
    expiresIn: 3600, // 1 hour
  },
  headers: request.headers,
});

When to Use Which

Use CaseUse HTTP EndpointsUse auth.api.* Methods
Client-side auth✅ Yes❌ No
Server middleware❌ No✅ Yes
Background jobs❌ No✅ Yes
Admin dashboards✅ Yes (from client)✅ Yes (from server)
Custom auth flows❌ No✅ Yes
Mobile apps✅ Yes❌ No
API routes✅ Yes (proxy to handler)✅ Yes (direct calls)

Example: Protected Route Middleware

import { Hono } from "hono";
import { createAuth } from "./auth";
import { createDatabase } from "./db";

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

// Middleware using server-side API
app.use("/api/protected/*", async (c, next) => {
  const db = createDatabase(c.env.DB);
  const auth = createAuth(db, c.env);

  // Use server-side method
  const session = await auth.api.getSession({
    headers: c.req.raw.headers,
  });

  if (!session) {
    return c.json({ error: "Unauthorized" }, 401);
  }

  // Attach to context
  c.set("user", session.user);
  c.set("session", session.session);

  await next();
});

// Protected route
app.get("/api/protected/profile", async (c) => {
  const user = c.get("user");
  return c.json({ user });
});

Discovering Available Endpoints

Use the OpenAPI plugin to see all endpoints in your configuration:

import { betterAuth } from "better-auth";
import { openAPI } from "better-auth/plugins";

export const auth = betterAuth({
  database: /* ... */,
  plugins: [
    openAPI(), // Adds /api/auth/reference endpoint
  ],
});

Interactive documentation: Visit http://localhost:8787/api/auth/reference

This shows a Scalar UI with:

  • ✅ All available endpoints grouped by feature
  • ✅ Request/response schemas with types
  • ✅ Try-it-out functionality (test endpoints in browser)
  • ✅ Authentication requirements
  • ✅ Code examples in multiple languages

Programmatic access:

const schema = await auth.api.generateOpenAPISchema();
console.log(JSON.stringify(schema, null, 2));
// Returns full OpenAPI 3.0 spec

Quantified Time Savings

Building from scratch (manual implementation):

  • Core auth endpoints (sign-up, sign-in, OAuth, sessions): 40 hours
  • Email verification & password reset: 10 hours
  • 2FA system (TOTP, backup codes, email OTP): 20 hours
  • Organizations (teams, invitations, RBAC): 60 hours
  • Admin panel (user management, impersonation): 30 hours
  • Testing & debugging: 50 hours
  • Security hardening: 20 hours

Total manual effort: ~220 hours (5.5 weeks full-time)

With better-auth:

  • Initial setup: 2-4 hours
  • Customization & styling: 2-4 hours

Total with better-auth: 4-8 hours

Savings: ~97% development time


Key Takeaway

better-auth provides 80+ production-ready endpoints covering:

  • ✅ Core authentication (20 endpoints)
  • ✅ 2FA & passwordless (15 endpoints)
  • ✅ Organizations & teams (35 endpoints)
  • ✅ Admin & user management (15 endpoints)
  • ✅ Social OAuth (auto-configured callbacks)
  • ✅ OpenAPI documentation (interactive UI)

You write zero endpoint code. Just configure features and call auth.handler().


Known Issues & Solutions

Issue 1: "d1Adapter is not exported" Error

Problem: Code shows import { d1Adapter } from 'better-auth/adapters/d1' but this doesn't exist.

Symptoms: TypeScript error or runtime error about missing export.

Solution: Use Drizzle or Kysely instead:

// ❌ 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 'kysely-d1'
database: {
  db: new Kysely({ dialect: new D1Dialect({ database: env.DB }) }),
  type: "sqlite"
}

Source: Verified from 4 production repositories using better-auth + D1


Issue 2: Schema Generation Fails

Problem: npx better-auth migrate doesn't create D1-compatible schema.

Symptoms: Migration SQL has wrong syntax or doesn't work with D1.

Solution: Use Drizzle Kit to generate migrations:

# Generate migration from Drizzle schema
npx drizzle-kit generate

# Apply to D1
wrangler d1 migrations apply my-app-db --remote

Why: Drizzle Kit generates SQLite-compatible SQL that works with D1.


Issue 3: "CamelCase" vs "snake_case" Column Mismatch

Problem: Database has email_verified but better-auth expects emailVerified.

Symptoms: Session reads fail, user data missing fields.

Solution: Use CamelCasePlugin with Kysely or configure Drizzle properly:

With Kysely:

import { CamelCasePlugin } from "kysely";

new Kysely({
  dialect: new D1Dialect({ database: env.DB }),
  plugins: [new CamelCasePlugin()], // Converts between naming conventions
})

With Drizzle: Define schema with camelCase from the start (as shown in examples).


Issue 4: D1 Eventual Consistency

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):

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);
        },
      },
    },
  });
}

Add to wrangler.toml:

[[kv_namespaces]]
binding = "SESSIONS_KV"
id = "your-kv-namespace-id"

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:

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 6: OAuth Redirect URI Mismatch

Problem: Social sign-in fails with "redirect_uri_mismatch" error.

Symptoms: Google/GitHub OAuth returns error after user consent.

Shortened here. Read the whole file on GitHub.

Signals

GitHub stars
52
Forks
5
Last commit
Nov 2025
Advanced
Catalog kind
skill
Gateway key
better-auth-ovachiever
Source
github.com/ovachiever/droid-tings