用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
直接命令不会经过审查 Prompt;运行前请先检查来源。
npx skills add https://github.com/tomevault-io/skills-registry --skill better-auth命令会保持在同一行。复制前请横向滚动并检查完整内容。
想先保存到本地?可下载 SkillsMP 当前能够提供的文件。
正在显示 SKILL.md
| name | better-auth |
| description | | Use when this capability is needed. |
Framework-agnostic TypeScript auth library. Plugin-based architecture, 40+ OAuth providers, 18+ framework integrations.
npm install better-auth
Scoped packages (as needed):
| Package | Use case |
|---|---|
@better-auth/passkey | WebAuthn/Passkey auth |
@better-auth/sso | SAML/OIDC enterprise SSO |
@better-auth/stripe | Stripe payments |
@better-auth/expo | React Native/Expo |
BETTER_AUTH_SECRET=<32+ chars, generate: openssl rand -base64 32>
BETTER_AUTH_URL=http://localhost:3000
DATABASE_URL=<connection string>
lib/auth.ts)import { betterAuth } from "better-auth";
export const auth = betterAuth({
database: process.env.DATABASE_URL, // or adapter instance
emailAndPassword: { enabled: true },
socialProviders: {
google: {
clientId: process.env.GOOGLE_CLIENT_ID!,
clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
},
},
plugins: [], // add plugins here
});
export type Session = typeof auth.$Infer.Session;
lib/auth-client.ts)import { createAuthClient } from "better-auth/react"; // or /vue, /svelte, /solid, /client
export const authClient = createAuthClient({
plugins: [], // add client plugins here
});
| Framework | File | Handler |
|---|---|---|
| Next.js App Router | app/api/auth/[...all]/route.ts | toNextJsHandler(auth) → export { GET, POST } |
| Next.js Pages | pages/api/auth/[...all].ts | toNextJsHandler(auth) → default export |
| Express | any | app.all("/api/auth/*splat", toNodeHandler(auth)) |
| Hono | route | app.on(["POST","GET"], "/api/auth/**", (c) => auth.handler(c.req.raw)) |
| SvelteKit | hooks.server.ts | svelteKitHandler({ auth, event }) |
| Astro | pages/api/auth/[...all].ts | toAstroHandler(auth) |
| Elysia | plugin | new Elysia().mount(auth.handler) |
See references/framework-integrations.md for all frameworks.
npx @better-auth/cli@latest migrate # Apply schema (built-in adapter)
npx @better-auth/cli@latest generate # Generate for Prisma/Drizzle
npx @better-auth/cli@latest generate --output prisma/schema.prisma
npx @better-auth/cli@latest generate --output src/db/auth-schema.ts
Re-run after adding/changing plugins.
auth): handles all auth logic, DB, sessionsauthClient): framework-specific hooks (useSession, signIn, signUp, signOut)auth.$Infer.Session, auth.$Infer.Session.user for full type safetycreateAuthClient<typeof auth>()| Method | Package | Config/Plugin | Reference |
|---|---|---|---|
| Email/Password | built-in | emailAndPassword: { enabled: true } | authentication.md |
| Social OAuth | built-in | socialProviders: { google: {...} } | authentication.md |
| Magic Link | built-in | magicLink() plugin | authentication.md |
| Passkey | @better-auth/passkey | passkey() plugin | authentication.md |
| Username | built-in | username() plugin | authentication.md |
| Email OTP | built-in | emailOtp() plugin | authentication.md |
| Phone Number | built-in | phoneNumber() plugin | authentication.md |
| Anonymous | built-in | anonymous() plugin | authentication.md |
Import from dedicated paths for tree-shaking: import { twoFactor } from "better-auth/plugins/two-factor" NOT from "better-auth/plugins".
| Plugin | Server Import | Client Import | Purpose |
|---|---|---|---|
twoFactor | better-auth/plugins/two-factor | twoFactorClient | TOTP, OTP, backup codes |
organization | better-auth/plugins/organization | organizationClient | Multi-tenant orgs, teams, RBAC |
admin | better-auth/plugins/admin | adminClient | User management, impersonation |
passkey | @better-auth/passkey | passkeyClient | WebAuthn/FIDO2 |
magicLink | better-auth/plugins/magic-link | magicLinkClient | Passwordless email links |
emailOtp | better-auth/plugins/email-otp | emailOtpClient | Email one-time passwords |
username | better-auth/plugins/username | usernameClient | Username-based auth |
phoneNumber | better-auth/plugins/phone-number | phoneNumberClient | Phone-based auth |
anonymous | better-auth/plugins/anonymous | anonymousClient | Guest sessions |
apiKey | better-auth/plugins/api-key | apiKeyClient | API key management |
bearer | better-auth/plugins/bearer | — | Bearer token auth |
jwt | better-auth/plugins/jwt | jwtClient |
Pattern: server plugin in auth({ plugins: [...] }) + client plugin in createAuthClient({ plugins: [...] }) + re-run CLI migrations.
See references/plugins.md for detailed usage and custom plugin creation.
| Adapter | Setup |
|---|---|
| SQLite | Pass better-sqlite3 or bun:sqlite instance |
| PostgreSQL | Pass pg.Pool instance |
| MySQL | Pass mysql2 pool |
| Prisma | prismaAdapter(prisma, { provider: "postgresql" }) from better-auth/adapters/prisma |
| Drizzle | drizzleAdapter(db, { provider: "pg" }) from better-auth/adapters/drizzle |
| MongoDB | mongodbAdapter(db) from better-auth/adapters/mongodb |
| Connection string | database: process.env.DATABASE_URL (uses built-in Kysely) |
Critical: Config uses ORM model name, NOT DB table name. Prisma model User mapping to table users → use modelName: "user".
Core schema tables: user, session, account, verification. Plugins add their own tables.
See references/setup.md for full database setup details.
Key options:
session: {
expiresIn: 60 * 60 * 24 * 7, // 7 days (default)
updateAge: 60 * 60 * 24, // refresh every 24h (default)
freshAge: 60 * 60 * 24, // require re-auth after 24h for sensitive ops
cookieCache: {
enabled: true,
maxAge: 300, // 5 min
strategy: "compact", // "compact" | "jwt" | "jwe"
},
}
secondaryStorage (Redis/KV): sessions go there by default, not DBcustomSession plugin: extend session with custom fieldsSee references/sessions.md for full session management details.
| DO | DON'T |
|---|---|
| Use 32+ char secret with high entropy | Commit secrets to version control |
Set baseURL with HTTPS in production | Disable CSRF check (disableCSRFCheck) |
Configure trustedOrigins for all frontends | Disable origin check |
| Enable rate limiting (on by default in prod) | Use "memory" rate limit storage in serverless |
Configure backgroundTasks.handler on serverless | Skip email verification setup |
Use "jwe" cookie cache for sensitive session data | Store OAuth tokens unencrypted if used for API calls |
Set revokeSessionsOnPasswordReset: true | Return specific error messages ("user not found") |
See references/security.md for complete security hardening guide.
session.storeSessionInDatabase: true to persist both"/api/auth/*splat" not "/api/auth/*" for catch-all routesnextCookies() plugin to auth config for server component session access| Issue | Fix |
|---|---|
| "Secret not set" | Add BETTER_AUTH_SECRET env var |
| "Invalid Origin" | Add domain to trustedOrigins |
| Cookies not setting | Check baseURL matches domain; enable secure cookies in prod |
| OAuth callback errors | Verify redirect URIs in provider dashboard match exactly |
| Type errors after adding plugin | Re-run CLI generate/migrate |
| Session null in RSC | Add nextCookies() plugin |
| 2FA redirect not working | Add twoFactorClient with onTwoFactorRedirect to client |
| File | When to read |
|---|---|
| setup.md | Setting up new project, configuring DB, route handlers |
| authentication.md | Implementing any auth method (email, social, passkey, magic link, etc.) |
| sessions.md | Configuring session expiry, caching, stateless mode, secondary storage |
| security.md | Hardening for production — rate limiting, CSRF, cookies, OAuth security |
| plugins.md | Using or creating plugins, plugin catalog |
| framework-integrations.md | Framework-specific setup (Next.js, Nuxt, SvelteKit, Hono, Express, etc.) |
| two-factor.md | Implementing 2FA (TOTP, OTP, backup codes, trusted devices) |
| organizations.md | Multi-tenant orgs, teams, invitations, RBAC |
| admin.md | User management, roles, banning, impersonation |
| hooks-and-middleware.md | Custom logic via before/after hooks, DB hooks, middleware |
Converted and distributed by TomeVault — claim your Tome and manage your conversions.
| JWT tokens |
multiSession | better-auth/plugins/multi-session | multiSessionClient | Multiple active sessions |
oauthProvider | better-auth/plugins/oauth-provider | — | Become OAuth provider |
oidcProvider | better-auth/plugins/oidc-provider | — | Become OIDC provider |
sso | @better-auth/sso | ssoClient | SAML/OIDC enterprise SSO |
openAPI | better-auth/plugins/open-api | — | API documentation |
customSession | better-auth/plugins/custom-session | — | Extend session data |
genericOAuth | better-auth/plugins/generic-oauth | genericOAuthClient | Custom OAuth providers |
oneTap | better-auth/plugins/one-tap | oneTapClient | Google One Tap |
基于 SOC 职业分类