Skip to main content
skill CX Codex

better-auth · oakoss — Claude Code skill: what it does, how to install

A skill that hands the agent a reference for better-auth: config, plugins, session strategies and the usual mistakes. Useful when a project needs login, 2FA or multi-tenant organizations.

MIT 114 installs ★ 29 updated 2026-08-17

Install into Claude Code · Skills CLI (Vercel) All methods and platforms ↓
npx skills add oakoss/agent-skills --skill better-auth -a claude-code
Open on GitHub

What better-auth does

This skill puts a better-auth reference in front of the agent: env vars, config options, the plugin catalogue, session strategies. better-auth itself is a self-hosted TypeScript auth framework with social login, 2FA, passkeys and organizations. The skill is pinned to [email protected], which is ESM-only from 1.4.0.

The traps get a table of their own. d1Adapter is out; on D1 you go through Drizzle or Kysely with provider: "sqlite". On TanStack Start, tanstackStartCookies() has to be the last plugin in the array. Login state lives in session?.user, since the session object itself is always truthy.

Before anything runs you need BETTER_AUTH_SECRET at 32 characters or more, plus BETTER_AUTH_URL. The CLI searches for auth.ts in ./, ./lib, ./utils and ./src only. Keep it somewhere else and the generator finds nothing. Touch the plugin list and you re-run npx @better-auth/cli@latest generate.

What it helps with

  • wire up Google and other social logins
  • add TOTP with backup codes to existing accounts
  • split tenants into organizations with roles
  • move a project off NextAuth or Clerk
  • debug a failing d1Adapter on Cloudflare D1

Example prompts for the agent

  • Set up better-auth in a Next.js app with email and password plus Google, taking the secret from BETTER_AUTH_SECRET.
  • Add the organization plugin with teams and roles, then regenerate the schema with npx @better-auth/cli@latest generate.
  • My session object is always truthy. Check that the code reads session?.user.

How to install better-auth

1Skills CLI (Vercel)

npx skills add oakoss/agent-skills --skill better-auth -a claude-code

2Manually: put the files in place

~/.claude/skills/better-auth/SKILL.md

Copy the whole skill folder; for one project use .claude/skills/better-auth/

Step by step, with commands for each platform: How to install skills in Claude Code: five ways

Questions about better-auth

How do I install the better-auth skill in Claude Code?

Run npx skills add oakoss/agent-skills --skill better-auth -a claude-code. The skill lands in ~/.claude/skills/better-auth/SKILL.md and loads in your next session.

What does the better-auth skill do?

It gives the agent a reference for better-auth: config options, plugins, session strategies, anti-patterns. The agent works from those tables instead of guessing the framework's API.

What has to be in place before setting up auth?

A BETTER_AUTH_SECRET of at least 32 characters, which you can generate with openssl rand -base64 32, and the app URL in BETTER_AUTH_URL. Keep auth.ts in ./, ./lib, ./utils or ./src so the CLI can find it.

Source text

SKILL.md · MIT
---
name: better-auth
description: |
  Self-hosted TypeScript auth framework with social auth, 2FA, passkeys, organizations, RBAC, and 15+ plugins. Supports Drizzle/Prisma/Kysely adapters. Self-hosted alternative to Clerk/Auth.js.

  Use when: configuring auth, adding plugins, social OAuth, multi-tenant SaaS, organizations with teams and RBAC, two-factor authentication (TOTP/OTP/backup codes), email verification, password reset flows, session management, rate limiting, CSRF and cookie security, Expo/mobile, D1 adapter errors, TanStack Start integration, additionalFields bugs, admin plugin, migrating from NextAuth, migrating from Clerk, migrating from Supabase Auth, or troubleshooting auth issues.
license: MIT
metadata:
  author: oakoss
  version: '1.2'
user-invocable: false
---

# better-auth

**Package**: [email protected] (ESM-only since v1.4.0)
**Docs**: <https://better-auth.com/docs> | **GitHub**: <https://github.com/better-auth/better-auth>

## Environment Setup

| Variable             | Purpose                                                               |
| -------------------- | --------------------------------------------------------------------- |
| `BETTER_AUTH_SECRET` | Encryption secret (min 32 chars). Generate: `openssl rand -base64 32` |
| `BETTER_AUTH_URL`    | Base URL (e.g., `https://example.com`)                                |

Only define `baseURL`/`secret` in config if env vars are NOT set. CLI looks for `auth.ts` in: `./`, `./lib`, `./utils`, or `./src`.

## Core Config Options

| Option             | Notes                                         |
| ------------------ | --------------------------------------------- |
| `appName`          | Optional display name                         |
| `baseURL`          | Only if `BETTER_AUTH_URL` not set             |
| `basePath`         | Default `/api/auth`. Set `/` for root.        |
| `secret`           | Only if `BETTER_AUTH_SECRET` not set          |
| `database`         | Required unless using stateless mode (v1.4+)  |
| `secondaryStorage` | Redis/KV for sessions and rate limits         |
| `emailAndPassword` | `{ enabled: true }` to activate               |
| `socialProviders`  | `{ google: { clientId, clientSecret }, ... }` |
| `plugins`          | Array of plugins                              |
| `trustedOrigins`   | CSRF whitelist                                |

## Plugin Reference

| Plugin        | Description                                                                        |
| ------------- | ---------------------------------------------------------------------------------- |
| twoFactor     | TOTP, email OTP, backup codes                                                      |
| organization  | Multi-tenant orgs, teams, invitations, RBAC                                        |
| admin         | User management, impersonation, banning                                            |
| passkey       | WebAuthn passwordless login                                                        |
| magicLink     | Email-based passwordless login                                                     |
| jwt           | JWT tokens with key rotation, JWKS                                                 |
| oauthProvider | Build your own OAuth 2.1 provider (separate `@better-auth/oauth-provider` package) |
| sso           | Enterprise SSO with OIDC, OAuth2, SAML 2.0 (separate `@better-auth/sso` package)   |
| scim          | Enterprise user provisioning (separate `@better-auth/scim` package)                |
| stripe        | Payment and subscription management                                                |
| bearer        | API token auth for mobile/CLI                                                      |
| apiKey        | Token-based auth with rate limits                                                  |
| oneTap        | Google One Tap frictionless sign-in                                                |
| anonymous     | Guest user access without PII                                                      |
| genericOAuth  | Custom OAuth providers with PKCE                                                   |
| emailOTP      | Email-based one-time password auth                                                 |
| phoneNumber   | Phone/SMS-based OTP sign-in                                                        |
| username      | Username-based sign-in (alternative to email)                                      |
| multiSession  | Multiple accounts in same browser                                                  |
| openAPI       | Interactive API docs at `/api/auth/reference`                                      |

## Session Strategies

| Strategy          | Format                  | Use Case          |
| ----------------- | ----------------------- | ----------------- |
| Compact (default) | Base64url + HMAC-SHA256 | Smallest, fastest |
| JWT               | Standard JWT            | Interoperable     |
| JWE               | A256CBC-HS512 encrypted | Most secure       |

## Getting Started

For new projects or first-time Better Auth setup, use the official interactive setup skill:

```bash
npx skills add better-auth/skills -s create-auth-skill
```

This walks through framework detection, database selection, auth method choices, plugin setup, and generates the initial configuration.

## Anti-Patterns

| Anti-Pattern                             | Correct Approach                                                               |
| ---------------------------------------- | ------------------------------------------------------------------------------ |
| Using `d1Adapter`                        | Use Drizzle or Kysely adapter with `provider: "sqlite"`                        |
| Using table name in config               | Use ORM model name, not DB table name                                          |
| Forgetting CLI after plugin changes      | Re-run `npx @better-auth/cli@latest generate`                                  |
| `tanstackStartCookies()` not last plugin | Must be the last plugin in array (TanStack Start)                              |
| Checking `session` for login state       | Check `session?.user` — session object is always truthy                        |
| Missing `nodejs_compat` flag             | Required in `wrangler.toml` for Cloudflare Workers                             |
| Kysely CamelCasePlugin with auth         | Use separate Kysely instance without the plugin                                |
| Using old `reactStartCookies` import     | Renamed to `tanstackStartCookies` from `better-auth/tanstack-start` in v1.4.14 |

## Common Mistakes

| Mistake                                                                | Correct Pattern                                                                                |
| ---------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- |
| Setting `baseURL` and `secret` in config when env vars are already set | Only define these in config if `BETTER_AUTH_URL` and `BETTER_AUTH_SECRET` env vars are NOT set |
| Using CommonJS require syntax with better-auth v1.4+                   | better-auth is ESM-only since v1.4.0; use `import` syntax exclusively                          |
| Not re-running CLI generate after adding or changing plugins           | Always run `npx @better-auth/cli@latest generate` after plugin changes to update DB schema     |
| Checking `session` object truthy state for login detection             | Check `session?.user` instead; the session object itself is always truthy                      |
| Using `d1Adapter` directly for Cloudflare D1                           | Use Drizzle or Kysely adapter with `provider: "sqlite"` for D1 compatibility                   |

## Breaking Changes

| Version | Change                                                                                           |
| ------- | ------------------------------------------------------------------------------------------------ |
| v1.4.14 | `reactStartCookies` renamed to `tanstackStartCookies` (import from `better-auth/tanstack-start`) |
| v1.4.6  | `allowImpersonatingAdmins` defaults to `false`                                                   |
| v1.4.0  | ESM-only (no CommonJS); SSO, SCIM, OAuth Provider moved to separate packages                     |
| v1.3.0  | Multi-team table structure: new `teamMembers` table needed                                       |

## Delegation

When working on auth, delegate to:

- `application-security` — Security architecture and threat modeling
- `database` — Drizzle ORM schema and migrations
- `tanstack-start` — TanStack Start integration patterns

## Resources

- **Docs**: <https://better-auth.com/docs>
- **Options Reference**: <https://better-auth.com/docs/reference/options>
- **LLMs.txt**: <https://better-auth.com/llms.txt>
- **Changelog**: <https://www.better-auth.com/changelogs>
- **TanStack Start**: <https://www.better-auth.com/docs/integrations/tanstack>
- **Expo**: <https://www.better-auth.com/docs/integrations/expo>

## References

- [Database Adapters](references/database-adapters.md) — Drizzle, Kysely, Prisma adapters, Cloudflare Workers factory pattern
- [Session Management](references/sessions.md) — Cookie cache, stateless sessions, storage priority, freshAge constraints
- [Plugins and Social Auth](references/plugins.md) — Plugin setup, OAuth 2.1 provider, admin RBAC, social provider scopes
- [Email and Password](references/email-password.md) — Verification, password reset, timing attack prevention, hashing (scrypt, argon2), token security
- [Two-Factor Authentication](references/two-factor.md) — TOTP, email/SMS OTP, backup codes, trusted devices, 2FA session flow
- [Organizations](references/organizations.md) — Multi-tenant orgs, teams, invitations, RBAC, dynamic access control, lifecycle hooks
- [Configuration](references/configuration.md) — User/account config, rate limiting, hooks, CSRF, trusted origins, cookie/OAuth security, production checklist
- [Framework Integration](references/frameworks.md) — TanStack Start setup, Expo/React Native, client imports, type safety
- [Migration Guides](references/migration-guides.md) — Migrate from NextAuth/Auth.js, Clerk, or Supabase Auth with schema mappings and session strategies
- [Troubleshooting](references/troubleshooting.md) — D1 consistency, CORS, OAuth redirect, admin 403, nanostore refresh, known bugs

© oakoss · MIT · oakoss/agent-skills

Similar skills

All skills for Backend and APIs →

better-auth by other authors comes first.

better-auth mrgoonie Walks your agent through Better Auth: email/password, OAuth, 2FA, passkeys and roles. Useful when a project needs sign-in and sessions. CX Codex +1 402installs better-auth giuseppe-trisciuoglio A skill with ready-made Better Auth patterns: NestJS backend, Drizzle ORM and PostgreSQL, social login, plus plugins like 2FA and passkey. CX Codex +1 3,800installs better-auth secondsky better-auth is a Claude Code skill for adding authentication and diagnosing Cloudflare D1 adapter errors. It also covers OAuth, two-factor authentication, and role-based access. CX Codex +1 511installs better-auth pproenca A TypeScript skill for Better Auth: instance setup, adapter choice, sessions and cookies, plugins, plus migration from another auth library. CX Codex +1 150installs better-auth-plugins bobmatnyc Guides coding agents when configuring Better Auth plugins in TypeScript projects. Covers two-factor auth, passkeys, JWT, and schema migrations. CX Codex +1 370installs better-auth-security-best-practices better-auth better-auth-security-best-practices hardens Better Auth deployments by configuring rate limits, CSRF rules, session caching, and OAuth token encryption. CX Codex +1 52,200installs better-auth-integrations bobmatnyc better-auth-integrations configures Better Auth route handlers in TypeScript web frameworks like Next.js, Remix, Hono, and Express. Solves cookie and header forwarding for SSR and server actions. CX Codex +1 371installs neon-auth neondatabase neon-auth is a Claude Code skill that sets up authentication with Neon Auth in a new app. It handles requests for login, sign-up, password resets, and OAuth. CX Codex +1 38,600installs safe-action-better-auth next-safe-action safe-action-better-auth is a Claude Code skill for adding Better Auth authentication and authorization to safe actions. It covers session middleware, access checks, and unauthenticated requests. CX Codex +1 499installs better-auth-scaffold pproenca better-auth-scaffold scaffolds Better Auth in a Next.js App Router project on Drizzle: file templates, three plugin presets, schema generation and migrations. CX Codex +1 143installs

From the same set106

The whole set →

Project sponsors

Companies that keep this analytics open