К основному содержанию
скилл CX Codex

better-auth · pproenca — скилл для Claude Code: что делает и как установить

Скилл по Better Auth для TypeScript: помогает поднять инстанс, выбрать адаптер, настроить сессии и перейти с другой auth-библиотеки.

MIT 150 установок ★ 227 обновлён 2026-08-15

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add pproenca/dot-skills --skill better-auth -a claude-code
Открыть на GitHub

Что делает better-auth

Скилл разбирает Better Auth — TypeScript-библиотеку аутентификации, не привязанную к конкретному фреймворку. Внутри 42 правила, разложенные по 8 категориям и отсортированные по важности: сначала настройка инстанса, адаптеры и роут-хендлеры, потом сессии, методы входа, безопасность, плагины и миграция. Правила собраны из официальной документации и гайдов по переезду.

Агент подхватывает скилл, когда вы пишете или правите код Better Auth, и даже если библиотека не названа, а речь идёт про TypeScript-аутентификацию, cookies сессий или OAuth-провайдеров. Есть разбор под Next.js (App и Pages Router), SvelteKit, Hono, Express, Nuxt, Astro и клиенты на React, Vue, Svelte. Отдельные правила чинят типовые поломки: сессия приходит null, провайдер отдаёт redirect_uri_mismatch, запрос падает с 403 по CSRF.

Порядок соблюдать придётся. В Next.js nextCookies() ставится последним плагином, а auth generate и миграция ORM идут до деплоя. Секрет и baseURL задаются отдельно для каждого окружения, trustedOrigins — без wildcard.

Какие задачи решает

  • Поднять инстанс Better Auth с адаптером под свой ORM
  • Починить redirect_uri_mismatch на OAuth-колбэке
  • Перевести проект с NextAuth или Clerk на Better Auth
  • Подключить 2FA и организации через плагины
  • Разобраться, почему getSession возвращает null на сервере

Примеры запросов агенту

  • Настрой Better Auth в Next.js: адаптер Prisma, catch-all роут в /api/auth/[...all] и клиент с inferAdditionalFields.
  • Перенеси вход с Clerk на Better Auth и сохрани текущих пользователей.
  • Добавь плагин 2FA и проверь, что nextCookies() стоит последним в списке плагинов.

Как установить better-auth

1Через Skills CLI (Vercel)

npx skills add pproenca/dot-skills --skill better-auth -a claude-code

2Вручную: положить файлы

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

Папка скилла целиком; для одного проекта — .claude/skills/better-auth/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о better-auth

Как установить better-auth в Claude Code?

Выполните npx skills add pproenca/dot-skills --skill better-auth -a claude-code. Файл скилла появится по пути ~/.claude/skills/better-auth/SKILL.md.

Что делает скилл better-auth?

Даёт агенту 42 правила по Better Auth в TypeScript, разбитые на 8 категорий: настройка, адаптеры БД, роут-хендлеры, сессии и cookies, методы входа, безопасность, плагины, миграция. Агент применяет их при написании и ревью кода.

С какими фреймворками и клиентами это работает?

Next.js (App и Pages Router), SvelteKit, Hono, Express, Nuxt, Astro, а также клиенты на React, Vue и Svelte. Есть правила под плагины 2FA, organization, admin, magicLink, JWT и passkey.

Исходный текст

SKILL.md · MIT
---
name: better-auth
description: Better Auth in TypeScript — setting up the auth instance, picking adapters, wiring framework route handlers, configuring sessions and cookies, adding plugins (2FA, organization, admin, magicLink, JWT), or porting from NextAuth/Auth.js, Clerk, Auth0, or Supabase Auth. Covers Next.js, SvelteKit, Hono, Express, Nuxt, Astro, and React/Vue/Svelte clients. Trigger when writing, reviewing, or migrating Better Auth code — and even when the user doesn't explicitly mention Better Auth but is working on TypeScript authentication, session cookies, OAuth providers, or auth-library migration. Contains 42 rules organized by impact across 8 categories.
---
# Better Auth Best Practices

Implementation and migration guide for [Better Auth](https://www.better-auth.com), the framework-agnostic TypeScript authentication and authorization library. This skill contains 42 rules organized by impact across 8 categories, derived from the official documentation and migration guides.

## When to Apply

Reference these guidelines when:

- Setting up a fresh Better Auth instance (config, adapter, route handler, client)
- Wiring framework-specific integrations (Next.js App/Pages Router, SvelteKit, Hono, Express, Nuxt, Astro)
- Configuring sessions, cookies, and security (rate limit, trusted origins, password hashing)
- Adding plugins: 2FA, organization, admin, magicLink, JWT, passkey, multi-session
- Migrating from another auth library (NextAuth/Auth.js, Clerk, Auth0, Supabase Auth)
- Debugging "session is null" / "redirect_uri_mismatch" / 403 CSRF errors
- Reviewing PRs that touch `lib/auth.ts`, `auth-client.ts`, or `/api/auth/` route handlers

## Rule Categories by Priority

| Priority | Category | Impact | Prefix |
|----------|----------|--------|--------|
| 1 | Setup & Configuration | CRITICAL | `setup-` |
| 2 | Database Adapters & Schema | CRITICAL | `db-` |
| 3 | API Route Handlers | CRITICAL | `route-` |
| 4 | Session & Cookies | HIGH | `session-` |
| 5 | Auth Methods & Providers | HIGH | `auth-` |
| 6 | Security & Hardening | HIGH | `security-` |
| 7 | Plugins & Extensions | MEDIUM | `plugins-` |
| 8 | Migration from Other Auth | MEDIUM | `migrate-` |

## Quick Reference

### 1. Setup & Configuration (CRITICAL)

- [`setup-secret`](references/setup-secret.md) — Set a strong `BETTER_AUTH_SECRET` per environment
- [`setup-base-url`](references/setup-base-url.md) — Configure an explicit `baseURL` per environment
- [`setup-client-base-url`](references/setup-client-base-url.md) — Match the client `baseURL` to the server
- [`setup-singleton`](references/setup-singleton.md) — Export a single auth instance from a server-only module
- [`setup-trusted-origins`](references/setup-trusted-origins.md) — Configure `trustedOrigins` for all non-baseURL callers

### 2. Database Adapters & Schema (CRITICAL)

- [`db-adapter-selection`](references/db-adapter-selection.md) — Pick the adapter that matches your ORM
- [`db-schema-generate`](references/db-schema-generate.md) — Run `auth generate` then ORM migrate before every deploy
- [`db-additional-fields`](references/db-additional-fields.md) — Extend the user schema via `additionalFields`
- [`db-plugin-schema-customization`](references/db-plugin-schema-customization.md) — Rename plugin tables via the `schema` option
- [`db-database-hooks`](references/db-database-hooks.md) — Use `databaseHooks` for cross-cutting logic
- [`db-connection-pooling`](references/db-connection-pooling.md) — Share one pooled DB client with the rest of your app

### 3. API Route Handlers (CRITICAL)

- [`route-mount-catchall`](references/route-mount-catchall.md) — Mount the catch-all handler at `/api/auth/[...all]`
- [`route-runtime-selection`](references/route-runtime-selection.md) — Use the Node.js runtime for middleware that calls `auth.api`
- [`route-no-body-consumers`](references/route-no-body-consumers.md) — Mount auth before any body-parsing middleware

### 4. Session & Cookies (HIGH)

- [`session-server-vs-client`](references/session-server-vs-client.md) — Use `auth.api.getSession` on server, `authClient.useSession` on client
- [`session-expiry-tuning`](references/session-expiry-tuning.md) — Configure `expiresIn` and `updateAge` together
- [`session-cookie-cache`](references/session-cookie-cache.md) — Enable `cookieCache` to cut session DB lookups
- [`session-cookie-attributes`](references/session-cookie-attributes.md) — Set `sameSite`, `secure`, `partitioned` for cross-site flows
- [`session-cross-subdomain`](references/session-cross-subdomain.md) — Enable `crossSubDomainCookies` for multi-subdomain apps
- [`session-customsession-fields`](references/session-customsession-fields.md) — Use `customSession` to add computed fields

### 5. Auth Methods & Providers (HIGH)

- [`auth-require-email-verification`](references/auth-require-email-verification.md) — Enable `requireEmailVerification` with `sendVerificationEmail`
- [`auth-oauth-redirect-uri`](references/auth-oauth-redirect-uri.md) — Match OAuth `redirectURI` exactly with the provider console
- [`auth-oauth-env-vars`](references/auth-oauth-env-vars.md) — Load OAuth credentials from environment, never inline
- [`auth-magic-link-setup`](references/auth-magic-link-setup.md) — Implement `sendMagicLink` before enabling the `magicLink` plugin
- [`auth-client-sign-in-helpers`](references/auth-client-sign-in-helpers.md) — Use `authClient.signIn.social` with `callbackURL`
- [`auth-infer-additional-fields`](references/auth-infer-additional-fields.md) — Add `inferAdditionalFields` to the client for type sync

### 6. Security & Hardening (HIGH)

- [`security-rate-limit`](references/security-rate-limit.md) — Enable `rateLimit` with persistent storage in production
- [`security-password-hash-interop`](references/security-password-hash-interop.md) — Override hash function when migrating from bcrypt/argon2
- [`security-revoke-on-password-reset`](references/security-revoke-on-password-reset.md) — Enable `revokeSessionsOnPasswordReset`
- [`security-min-password-length`](references/security-min-password-length.md) — Set `minPasswordLength` to at least 10
- [`security-trusted-origins-strict`](references/security-trusted-origins-strict.md) — Never wildcard `trustedOrigins`

### 7. Plugins & Extensions (MEDIUM)

- [`plugins-next-cookies-last`](references/plugins-next-cookies-last.md) — Place `nextCookies()` as the LAST plugin in Next.js
- [`plugins-two-factor-issuer`](references/plugins-two-factor-issuer.md) — Set `appName` as the 2FA issuer
- [`plugins-shared-access-control`](references/plugins-shared-access-control.md) — Define `ac` + roles once, share server/client
- [`plugins-pair-client-server`](references/plugins-pair-client-server.md) — Pair every server plugin with its client counterpart
- [`plugins-organization-active-context`](references/plugins-organization-active-context.md) — Set active organization on session
- [`plugins-jwt-when-to-use`](references/plugins-jwt-when-to-use.md) — Use the `jwt` plugin only for external service consumers
- [`plugins-admin-impersonation`](references/plugins-admin-impersonation.md) — Use admin plugin's `impersonate` method for support access

### 8. Migration from Other Auth (MEDIUM)

- [`migrate-parallel-cutover`](references/migrate-parallel-cutover.md) — Run Better Auth alongside legacy auth during cutover
- [`migrate-oauth-account-mapping`](references/migrate-oauth-account-mapping.md) — Map legacy OAuth identities to `account` rows
- [`migrate-force-allow-id`](references/migrate-force-allow-id.md) — Use `forceAllowId` to preserve existing user IDs
- [`migrate-nextauth-schema-mapping`](references/migrate-nextauth-schema-mapping.md) — Map NextAuth v5 columns field-by-field

## How to Use

For a fresh implementation, read in priority order: start with all `setup-` rules, then `db-`, then `route-` — these CRITICAL categories must be correct or nothing else works. After the foundation, pick the rules that match your scope: `session-` for cookie/expiry tuning, `auth-` for provider configuration, `security-` for production hardening.

For a migration from another auth library, read `migrate-parallel-cutover` first (strategy), then `security-password-hash-interop` (preserve user passwords), then `migrate-oauth-account-mapping` and `migrate-nextauth-schema-mapping` (data layout).

Read individual reference files for detailed explanations, incorrect vs. correct code examples, and links to the canonical Better Auth documentation.

## Reference Files

| File | Description |
|------|-------------|
| [references/_sections.md](references/_sections.md) | Category definitions ordered by impact |
| [assets/templates/_template.md](assets/templates/_template.md) | Template for adding new rules |
| [metadata.json](metadata.json) | Version, references, and discipline metadata |

© pproenca · MIT · pproenca/dot-skills

Похожие скиллы

Все скиллы по теме «Бэкенд и API» →

Сначала — better-auth от других авторов.

better-auth mrgoonie Проводит по подключению Better Auth: email-пароли, OAuth, 2FA, passkeys и роли. Встраивает вход и сессии в TypeScript-проект. CX Codex +1 402установок better-auth giuseppe-trisciuoglio Скилл с готовыми шаблонами Better Auth: подключение к NestJS, Drizzle ORM и PostgreSQL, вход через соцсети и плагины вроде 2FA и passkey. CX Codex +1 3 800установок better-auth secondsky Скилл better-auth для Claude Code помогает подключить аутентификацию и разобраться с ошибками адаптера Cloudflare D1. Он также покрывает OAuth, двухфакторную защиту и роли доступа. CX Codex +1 511установок better-auth oakoss Подгружает агенту справочник по better-auth: конфиг, плагины, стратегии сессий и типовые ошибки. Даёт справку при настройке входа, 2FA и организаций. CX Codex +1 114установок better-auth-security-best-practices better-auth Скилл better-auth-security-best-practices настраивает защиту Better Auth: ограничивает частоту запросов, проверяет происхождение, шифрует токены и защищает пользовательские сессии. CX Codex +1 52 200установок neon-auth neondatabase Скилл neon-auth для Claude Code настраивает аутентификацию через Neon Auth в новом приложении. Он подключается к задачам входа, регистрации, сброса пароля и OAuth. CX Codex +1 38 600установок better-auth-core bobmatnyc Скилл better-auth-core для Claude Code и других агентов: настраивает Better Auth в TypeScript — инстанс, БД, обработчики, клиент и сессии. CX Codex +1 376установок better-auth-integrations bobmatnyc Скилл better-auth-integrations помогает подключить Better Auth к веб-фреймворкам на TypeScript: Next.js, SvelteKit, Remix, Express и Hono. Настраивает обработчики /api/auth/* и работу с cookies в SSR. CX Codex +1 371установок nuxt-better-auth onmax Скилл nuxt-better-auth помогает настраивать аутентификацию в Nuxt через @nuxtjs/better-auth, защищать маршруты и работать с сессиями. Пригодится при внедрении Better Auth. CX Codex +1 2 100установок safe-action-better-auth next-safe-action Скилл safe-action-better-auth для Claude Code помогает добавить аутентификацию и проверку доступа к safe actions через Better Auth. Он включается при настройке middleware, сессии и отказа в доступе. CX Codex +1 499установок

Из того же набора139

Весь набор →
expo-design-system Скилл expo-design-system для Claude Code помогает строить и проверять общие компоненты Expo и React Native для веба и iOS. Подключается при работе с токенами, темами и повторно используемым интерфейсом. CX Codex +1 156установок complexity-optimizer Скилл complexity-optimizer находит узкие места алгоритмической сложности в коде и готовит отчёт с безопасными исправлениями. CX Codex +1 156установок nextjs-bundle-optimizer Скилл nextjs-bundle-optimizer для Claude Code измеряет размер бандла и время сборки Next.js и помогает проверять оптимизации по одной. Проверяет оптимизации при росте First Load JS или замедлении сборки. CX Codex +1 152установок implementation-design-patterns Скилл implementation-design-patterns для Claude Code помогает определить паттерн Gang of Four по описанию задачи и понять, когда его применять или избегать. CX Codex +1 151установок diataxis Скилл diataxis раскладывает техническую документацию на четыре режима: туториал, инструкция, справочник, объяснение. Помогает решить, что писать на конкретной странице. CX Codex +1 149установок drizzle-sqlite-scaffold Скилл drizzle-sqlite-scaffold генерирует готовый boilerplate для Drizzle ORM + SQLite: конфиг, клиент с прагмами, схемы таблиц, CRUD-модули и валидаторы. Срабатывает на фразы вроде «добавь таблицу для X» или «настрой БД». CX Codex +1 149установок same-results-less-code Скилл same-results-less-code помогает находить лишнюю сложность при ревью и рефакторинге, сохраняя поведение кода. Он дополняет линтеры анализом структуры и моделей. CX Codex +1 148установок codebase-comprehension-algorithms Скилл codebase-comprehension-algorithms раскладывает незнакомый репозиторий на функциональные домены: какие файлы стоят за фичей и где проходит архитектурный каркас. CX Codex +1 148установок

Ещё в каталоге

Спонсоры проекта

Компании, которые помогают держать аналитику открытой