agentleFS
charlietlambcharlietlamb/ferix/.claude/skills/better-auth-best-practices/SKILL.md

better-auth-best-practices

Skill10 starsChanged 10 months agoMITView on GitHub

Skill for integrating Better Auth - the comprehensive TypeScript authentication framework.

49 other projects use a version of this, 38 of them edited; 34 of 37 edited versions we compared changed its rules; 0 new projects in the last 4 weeks, against 5 the 4 before.

How people change it

34 of 37 edited versions changed its rules, and some changes recur.

Of the 37 edited versions we compared: 3 keep every rule, 34 made changes of their own.

Rules people add

  1. Create auth.ts with database + configadded by 34 of 34
  2. Create route handler for your frameworkadded by 34 of 34
  3. Verify: call GET /api/auth/ok — should return { status: "ok" }added by 34 of 34
  4. A rule we can't quote: its licence doesn't allow itadded by 5 of 34
  5. A rule we can't quote: its licence doesn't allow itadded by 5 of 34
  6. A rule we can't quote: its licence doesn't allow itadded by 5 of 34
  7. A rule we can't quote: its licence doesn't allow itadded by 5 of 34
  8. A rule we can't quote: its licence doesn't allow itadded by 5 of 34

We split this file and each edited version into the rules they give an agent and match them by wording. A version that adds no rule of its own and has not changed since this file last did reads as an older text, so what it lacks is not counted as dropped. We keep no past texts of a file, so that is inferred, and an edited version that started from an older text still counts its gaps as drops.

Adopted by

Cooling: 0 new projects took it in the last 4 weeks, 0× the 4 weeks before.thin data

Week of Sep 20: 2 new projectsWeek of Sep 27: 1 new projectWeek of Oct 4: 0 new projectsWeek of Oct 11: 2 new projectsWeek of Oct 18: 0 new projectsWeek of Oct 25: 0 new projectsWeek of Nov 1: 0 new projectsWeek of Nov 8: 0 new projects
Sep 2026Oct 2026Nov 2026
New projects taking a version of this file each week, over the 8 weeks our latest run read: only 5 in all, so this is a hint, not a trend.

Most recently taken up by

Used with

Projects with it also use organization-best-practices, email-and-password-best-practices and 10 more.

Other files people use alongside this one.

Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
  • lukevellaSkill

    organization-best-practices

    This skill provides guidance and enforcement rules for implementing multi-tenant organizations, teams, and role-based access control using Better Auth's organization plugin.

    Also in 7 projects that use this

  • lukevellaSkill

    email-and-password-best-practices

    This skill provides guidance and enforcement rules for implementing secure email and password authentication using Better Auth.

    Also in 7 projects that use this

  • wdchenxyzSkill

    create-auth

    Scaffold and implement authentication in TypeScript/JavaScript apps using Better Auth. Detect frameworks, configure database adapters, set up route handlers, add OAuth providers, and create auth UI pages. Use when users want to add login, sign-up, or authentication to a new or existing project with Better Auth.

    Also in 5 projects that use this

  • NVIDIASkill

    build-ui

    Orchestrate Kumo UI ticket work from GitHub issue analysis through implementation, validation, and optional PR creation.

    Also in 3 projects that use this

  • JasonPaffSkill

    tanstack-table

    Build headless data tables with TanStack Table v8. Server-side pagination, filtering, sorting, and virtualization for Cloudflare Workers + D1. Prevents 12 documented errors.

    Also in 3 projects that use this

  • Aver005Skill

    tanstack-query-best-practices

    TanStack Query (React Query) best practices for data fetching, caching, mutations, and server state management. Activate when building data-driven React applications with server state.

    Also in 3 projects that use this

  • +2 more from lukevella

The file

We split this skill into the rules it gives an agent

6 rules. 1 is common, 0 are distinctive, and 5 are very specific to this project.

  • 1

    Common

    Most of the 39 edited versions we read keep these.

  • 0

    Distinctive

    This author's own choices. Worth a look.

  • 5

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Only define baseURL/secret in config if env vars are NOT set.

    line 20
  2. Very specific:

    ORM adapters: Import from better-auth/adapters/drizzle, better-auth/adapters/prisma, better-auth/adapters/mongodb.

    line 55
  3. Very specific:

    If secondaryStorage defined → sessions go there (not DB)

    line 64
  4. Very specific:

    No database + cookieCache → fully stateless mode

    line 66
  5. Very specific:

    Import from: better-auth/client (vanilla), better-auth/react, better-auth/vue, better-auth/svelte, better-auth/solid.

    line 135
  6. Common:

    Stateless mode: - No DB = session in cookie only, logout on cache expiry

    line 155

“Common” is measured: kept by at least 6 in 10 of the 39 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Better Auth Integration Guide

Always consult better-auth.com/docs for code examples and latest API.

Better Auth is a TypeScript-first, framework-agnostic auth framework supporting email/password, OAuth, magic links, passkeys, and more via plugins.


Quick Reference

Environment Variables

  • 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.

File Location

CLI looks for auth.ts in: ./, ./lib, ./utils, or under ./src. Use --config for custom path.

CLI Commands

  • npx @better-auth/cli@latest migrate - Apply schema (built-in adapter)
  • npx @better-auth/cli@latest generate - Generate schema for Prisma/Drizzle
  • npx @better-auth/cli mcp --cursor - Add MCP to AI tools

Re-run after adding/changing plugins.


Core Config Options

OptionNotes
appNameOptional display name
baseURLOnly if BETTER_AUTH_URL not set
basePathDefault /api/auth. Set / for root.
secretOnly if BETTER_AUTH_SECRET not set
databaseRequired for most features. See adapters docs.
secondaryStorageRedis/KV for sessions & rate limits
emailAndPassword{ enabled: true } to activate
socialProviders{ google: { clientId, clientSecret }, ... }
pluginsArray of plugins
trustedOriginsCSRF whitelist

Database

Direct connections: Pass pg.Pool, mysql2 pool, better-sqlite3, or bun:sqlite instance.

ORM adapters: Import from better-auth/adapters/drizzle, better-auth/adapters/prisma, better-auth/adapters/mongodb.

Critical: Better Auth uses adapter model names, NOT underlying table names. If Prisma model is User mapping to table users, use modelName: "user" (Prisma reference), not "users".


Session Management

Storage priority:

  1. If secondaryStorage defined → sessions go there (not DB)
  2. Set session.storeSessionInDatabase: true to also persist to DB
  3. No database + cookieCache → fully stateless mode

Cookie cache strategies:

  • compact (default) - Base64url + HMAC. Smallest.
  • jwt - Standard JWT. Readable but signed.
  • jwe - Encrypted. Maximum security.

Key options: session.expiresIn (default 7 days), session.updateAge (refresh interval), session.cookieCache.maxAge, session.cookieCache.version (change to invalidate all sessions).


User & Account Config

User: user.modelName, user.fields (column mapping), user.additionalFields, user.changeEmail.enabled (disabled by default), user.deleteUser.enabled (disabled by default).

Account: account.modelName, account.accountLinking.enabled, account.storeAccountCookie (for stateless OAuth).

Required for registration: email and name fields.


Email Flows

  • emailVerification.sendVerificationEmail - Must be defined for verification to work
  • emailVerification.sendOnSignUp / sendOnSignIn - Auto-send triggers
  • emailAndPassword.sendResetPassword - Password reset email handler

Security

In advanced:

  • useSecureCookies - Force HTTPS cookies
  • disableCSRFCheck - ⚠️ Security risk
  • disableOriginCheck - ⚠️ Security risk
  • crossSubDomainCookies.enabled - Share cookies across subdomains
  • ipAddress.ipAddressHeaders - Custom IP headers for proxies
  • database.generateId - Custom ID generation or "serial"/"uuid"/false

Rate limiting: rateLimit.enabled, rateLimit.window, rateLimit.max, rateLimit.storage ("memory" | "database" | "secondary-storage").


Hooks

Endpoint hooks: hooks.before / hooks.after - Array of { matcher, handler }. Use createAuthMiddleware. Access ctx.path, ctx.context.returned (after), ctx.context.session.

Database hooks: databaseHooks.user.create.before/after, same for session, account. Useful for adding default values or post-creation actions.

Hook context (ctx.context): session, secret, authCookies, password.hash()/verify(), adapter, internalAdapter, generateId(), tables, baseURL.


Plugins

Import from dedicated paths for tree-shaking:

import { twoFactor } from "better-auth/plugins/two-factor"

NOT from "better-auth/plugins".

Popular plugins: twoFactor, organization, passkey, magicLink, emailOtp, username, phoneNumber, admin, apiKey, bearer, jwt, multiSession, sso, oauthProvider, oidcProvider, openAPI, genericOAuth.

Client plugins go in createAuthClient({ plugins: [...] }).


Client

Import from: better-auth/client (vanilla), better-auth/react, better-auth/vue, better-auth/svelte, better-auth/solid.

Key methods: signUp.email(), signIn.email(), signIn.social(), signOut(), useSession(), getSession(), revokeSession(), revokeSessions().


Type Safety

Infer types: typeof auth.$Infer.Session, typeof auth.$Infer.Session.user.

For separate client/server projects: createAuthClient<typeof auth>().


Common Gotchas

  1. Model vs table name - Config uses ORM model name, not DB table name
  2. Plugin schema - Re-run CLI after adding plugins
  3. Secondary storage - Sessions go there by default, not DB
  4. Cookie cache - Custom session fields NOT cached, always re-fetched
  5. Stateless mode - No DB = session in cookie only, logout on cache expiry
  6. Change email flow - Sends to current email first, then new email

Resources

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.