Skip to content
better-auth-best-practices logo

Better Auth 統合ガイド

better-auth-best-practices

Better Auth(TypeScript 認証フレームワーク)の統合ガイド。セットアップ、セッション管理、プラグイン、セキュリティ設定に精通。

SKILL.md

Full skill instructions

Better Auth 統合ガイド

コード例と最新 API は better-auth.com/​docs を必ず参照すること。

Better Auth は TypeScript ファーストでフレームワーク非依存の認証フレームワーク。メール/パスワード、OAuth、マジックリンク、パスキーなどをプラグインでサポート。


クイックリファレンス

環境変数

  • BETTER_AUTH_SECRET - 暗号化シークレット(最低 32 文字)。生成: openssl rand -base64 32
  • BETTER_AUTH_URL - ベース URL(例: https://example.com)

環境変数が設定されていない場合のみ、config で baseURL/secret を定義する。

ファイルの配置場所

CLI は auth.ts を以下の順で検索: ./, ./​lib, ./​utils, または ./​src 配下。カスタムパスは --config で指定。

CLI コマンド

  • npx @better-auth/​cli@latest migrate - スキーマ適用(組み込みアダプター)
  • npx @better-auth/​cli@latest generate - Prisma/​Drizzle 用スキーマ生成
  • npx @better-auth/​cli mcp --cursor - AI ツールに MCP を追加

プラグインの追加・変更後は必ず再実行すること。


コア設定オプション

オプション説明
appName表示名(任意)
baseURLBETTER_AUTH_URL 未設定時のみ
basePathデフォルト /​api/​auth。ルートに配置する場合は /
secretBETTER_AUTH_SECRET 未設定時のみ
databaseほとんどの機能で必須。アダプタードキュメント参照
secondaryStorageセッション・レート制限用の Redis/​KV
emailAndPassword{ enabled: true } で有効化
socialProviders{ google: { clientId, clientSecret }, ... }
pluginsプラグインの配列
trustedOriginsCSRF ホワイトリスト

データベース

直接接続: pg.Pool、mysql2 プール、better-sqlite3、または bun:sqlite インスタンスを渡す。

ORM アダプター: better-auth/​adapters/​drizzle、better-auth/​adapters/​prisma、better-auth/​adapters/​mongodb からインポート。

重要: Better Auth はアダプターのモデル名を使用し、DB のテーブル名は使わない。Prisma モデルが User でテーブルが users にマッピングされている場合、modelName: "user"(Prisma の参照名)を使い、"users" ではない。


セッション管理

ストレージの優先順位:

  1. secondaryStorage が定義されている場合 → セッションはそこに保存(DB ではない)
  2. DB にも永続化する場合は session.storeSessionInDatabase: true を設定
  3. DB なし + cookieCache → 完全ステートレスモード

Cookie キャッシュ戦略:

  • compact(デフォルト)- Base64url + HMAC。最小サイズ
  • jwt - 標準 JWT。読み取り可能だが署名付き
  • jwe - 暗号化。最大セキュリティ

主要オプション: session.expiresIn(デフォルト 7 日)、session.updateAge(リフレッシュ間隔)、session.cookieCache.maxAge、session.cookieCache.version(変更するとすべてのセッションを無効化)。


ユーザーとアカウント設定

ユーザー: user.modelName、user.fields(カラムマッピング)、user.additionalFields、user.changeEmail.enabled(デフォルト無効)、user.deleteUser.enabled(デフォルト無効)。

アカウント: account.modelName、account.accountLinking.enabled、account.storeAccountCookie(ステートレス OAuth 用)。

登録に必須: email と name フィールド。


メールフロー

  • emailVerification.sendVerificationEmail - 認証を機能させるには定義が必須
  • emailVerification.sendOnSignUp / sendOnSignIn - 自動送信トリガー
  • emailAndPassword.sendResetPassword - パスワードリセットメールハンドラー

セキュリティ

advanced 内:

  • useSecureCookies - HTTPS Cookie を強制
  • disableCSRFCheck - セキュリティリスクあり
  • disableOriginCheck - セキュリティリスクあり
  • crossSubDomainCookies.enabled - サブドメイン間で Cookie を共有
  • ipAddress.ipAddressHeaders - プロキシ用カスタム IP ヘッダー
  • database.generateId - カスタム ID 生成、または "serial"/"uuid"/false

レート制限: rateLimit.enabled、rateLimit.window、rateLimit.max、rateLimit.storage("memory" | "database" | "secondary-storage")。


フック

エンドポイントフック: hooks.before / hooks.after - { matcher, handler } の配列。createAuthMiddleware を使用。ctx.path、ctx.context.returned(after)、ctx.context.session にアクセス可能。

データベースフック: databaseHooks.user.create.before/​after、session、account も同様。デフォルト値の追加や作成後のアクションに有用。

フックコンテキスト (ctx.context): session、secret、authCookies、password.hash()/verify()、adapter、internalAdapter、generateId()、tables、baseURL。


プラグイン

ツリーシェイキングのため専用パスからインポート:

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

from "better-auth/​plugins" からはインポートしない。

主要プラグイン: twoFactor、organization、passkey、magicLink、emailOtp、username、phoneNumber、admin、apiKey、bearer、jwt、multiSession、sso、oauthProvider、oidcProvider、openAPI、genericOAuth。

クライアントプラグインは createAuthClient({ plugins: [...] }) に配置。


クライアント

インポート元: better-auth/​client(バニラ)、better-auth/​react、better-auth/​vue、better-auth/​svelte、better-auth/​solid。

主要メソッド: signUp.email()、signIn.email()、signIn.social()、signOut()、useSession()、getSession()、revokeSession()、revokeSessions()。


型安全性

型の推論: typeof auth.$Infer.Session、typeof auth.$Infer.Session.user。

クライアント/サーバーが別プロジェクトの場合: createAuthClient<typeof auth>()。


よくあるハマりどころ

  1. モデル名 vs テーブル名 - 設定では ORM のモデル名を使用し、DB のテーブル名は使わない
  2. プラグインのスキーマ - プラグイン追加後に CLI を再実行する
  3. セカンダリストレージ - セッションはデフォルトでそちらに保存され、DB には保存されない
  4. Cookie キャッシュ - カスタムセッションフィールドはキャッシュされず、常に再取得される
  5. ステートレスモード - DB なし = セッションは Cookie のみ、キャッシュ期限でログアウト
  6. メールアドレス変更フロー - まず現在のメールに送信、その後新しいメールに送信

リソース

More skills from diegosouzapw

accessibility logo
diegosouzapw/awesome-omni-skill

accessibility

Accessibility guidelines for VS Code features — covers accessibility help dialogs, accessible views, verbosity settings, accessibility signals, ARIA alerts/status announcements, keyboard navigation, and ARIA labels/roles. Applies to both new interactive UI surfaces and updates to existing feature...

62 1
View
mermaid-diagrams logo
diegosouzapw/awesome-omni-skill

mermaid-diagrams

Mermaid diagram creation for flowcharts, sequences, ERDs, and more. Generate diagrams from text in markdown files. Use for documentation, architecture diagrams, and visual representations. Triggers on mermaid, flowchart, sequence diagram, ERD, entity relationship, gantt chart, pie chart, class di...

62 1
View
tauri2-react-rust logo
diegosouzapw/awesome-omni-skill

tauri2-react-rust

Guides development of cross-platform desktop apps with Tauri 2, TypeScript, React, and Rust. Use when building Tauri apps, implementing IPC, designing Rust backend or TypeScript/React frontend, when researching or cloning a website (open site, snapshot elements), when verifying local dev or built...

62 1
View
fp-ts-errors logo
diegosouzapw/awesome-omni-skill

fp-ts-errors

Handle errors as values using fp-ts Either and TaskEither for cleaner, more predictable TypeScript code. Use when implementing error handling patterns with fp-ts.

62 0
View
ring:pre-dev-research logo
diegosouzapw/awesome-omni-skill

ring:pre-dev-research

Gate 0 research phase for pre-dev workflow. Dispatches 3 parallel research agents to gather codebase patterns, external best practices, and framework documentation BEFORE creating PRD/TRD. Outputs research.md with file:line references.

62 0
View
create-assistant logo
diegosouzapw/awesome-omni-skill

create-assistant

Create and configure Vapi voice AI assistants with models, voices, transcribers, tools, hooks, and advanced settings. Use when building voice agents, phone bots, customer support assistants, or any conversational AI that handles phone or web calls.

62 0
View
codex-headless logo
diegosouzapw/awesome-omni-skill

codex-headless

Delegiere Aufgaben an OpenAI Codex CLI im Headless-Mode. Nutzt ChatGPT Subscription (KEIN API Key). Nur Workspace-Zugriff, KEIN System-Zugriff. Auto-Accept mit --full-auto. Web-Recherche mit --search.

62 0
View
social-media-scheduler logo
diegosouzapw/awesome-omni-skill

social-media-scheduler

Generate a full week of social media content for any topic. Outputs platform-optimized posts for Twitter/X, LinkedIn, and Instagram with hashtags and posting times.

62 0
View
Data Privacy Compliance logo
diegosouzapw/awesome-omni-skill

Data Privacy Compliance

Data privacy and regulatory compliance specialist for GDPR, CCPA, HIPAA, and international data protection laws. Use when implementing privacy controls, conducting data protection impact assessments, ensuring regulatory compliance, or managing data subject rights. Expert in consent management, da...

62 0
View
triple-review logo
diegosouzapw/awesome-omni-skill

triple-review

Reviews a task using the TRIPLE protocol, as the review agent.

62 0
View
Tech Stack & Architecture Decision logo
diegosouzapw/awesome-omni-skill

Tech Stack & Architecture Decision

Define and document the technology stack and architecture decisions for a project. Use when the user needs to choose a tech stack, make architecture decisions, define infrastructure choices, or document technology selections. Triggers on requests like "define the tech stack", "choose technologies...

62 0
View

Popular AI tools

Kaiber logo
Video

Kaiber

Generate, edit, and beat-sync AI video with leading models in one workspace.

Paid
View
Vimcal logo
Productivity

Vimcal

The world's fastest calendar for remote work

Free
View

Transform Your Design with AI Designer by ImgCreator.ai

Freemium
View
Akool AI logo
Content & writing

Akool AI

Revolutionizing Video Production with AI-Powered Creativity

Paid
View

Extend an image past the frame and let AI fill the new aspect ratio.

Freemium
View
StarByFace logo
Security

StarByFace

Discover your celebrity doppelgänger with StarByFace!

Free
View
C

ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.

Freemium
View
Opus Clip logo
Coding & apps

Opus Clip

Opus.ai: Revolutionize Your Web Experience

Free
View