better-auth-best-practices
Skill này làm gì
Skill hướng dẫn AI cấu hình máy chủ, client, bộ chuyển đổi cơ sở dữ liệu, phiên làm việc và biến môi trường của Better Auth. Dành cho lập trình viên thêm xác thực vào dự án TypeScript.
Khi nào nên dùng
- ✓Khi bạn thêm đăng nhập bằng email và mật khẩu hoặc OAuth vào ứng dụng TypeScript.
- ✓Khi bạn thiết lập file auth.ts, bộ chuyển đổi cơ sở dữ liệu hoặc route handler của Better Auth.
- ✓Khi bạn cần thêm plugin Better Auth hoặc sửa các biến môi trường của nó.
Liên kết skill
https://github.com/trycompai/crm/blob/release/.agents/skills/better-auth-best-practices/SKILL.mdSao chép rồi dán vào AI của bạn (Claude, ChatGPT hoặc Cursor) và nhờ nó làm theo hướng dẫn.
Cách dùng
Cách dễ nhất: sao chép tin nhắn và dán vào AI của bạn. AI sẽ đọc skill và làm theo hướng dẫn.
Tin nhắn có sẵn để dán
Dành cho Claude Code, Codex hoặc Cursor: chạy lệnh trong thư mục dự án của bạn và skill sẽ được cài đặt.
Tải tệp SKILL.md về và thả vào thư mục skill của agent.
Ví dụ cách nhờ AI
“Bạn có thể thiết lập Better Auth trong ứng dụng TypeScript của tôi với đăng nhập bằng email và mật khẩu không?”
5 skill mới mỗi tuần. Đọc chỉ 1 phút.
Cách hoạt động
AI cài gói, đặt các biến bí mật và URL, tạo cấu hình xác thực, chạy migration cơ sở dữ liệu và kiểm tra endpoint sức khỏe.
Nội dung kỹ thuật (SKILL.md gốc)
Lấy nguyên văn từ GitHub, do tác giả viết bằng tiếng Anh.
Better Auth Integration Guide
Always consult better-auth.com/docs for code examples and latest API.
Setup Workflow
- Install:
npm install better-auth - Set env vars:
BETTER_AUTH_SECRETandBETTER_AUTH_URL - Create
auth.tswith database + config - Create route handler for your framework
- Run migrations:
- Built-in adapter:
npx @better-auth/cli@latest migrate - Drizzle:
npx @better-auth/cli@latest generate --output src/db/auth-schema.tsthennpx drizzle-kit push(dev) ornpx drizzle-kit generate && npx drizzle-kit migrate(prod) - Prisma:
npx @better-auth/cli@latest generate --output prisma/schema.prismathennpx prisma migrate dev
- Built-in adapter:
- Verify: call
GET /api/auth/ok— should return{ status: "ok" }
Quick Reference
Environment Variables
BETTER_AUTH_SECRET- Encryption secret (min 32 chars). Generate:openssl rand -base64 32BETTER_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/Drizzlenpx @better-auth/cli mcp --cursor- Add MCP to AI tools
Re-run after adding/changing plugins.
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 for most features. See adapters docs. |
secondaryStorage |
Redis/KV for sessions & rate limits |
emailAndPassword |
{ enabled: true } to activate |
socialProviders |
{ google: { clientId, clientSecret }, ... } |
plugins |
Array of plugins |
trustedOrigins |
CSRF whitelist |
Database
Direct connections: Pass pg.Pool, mysql2 pool, better-sqlite3, or bun:sqlite instance. For Postgres, also supports postgres (postgres.js) and @neondatabase/serverless.
ORM adapters: Import from better-auth/adapters/drizzle, better-auth/adapters/prisma, better-auth/adapters/mongodb.
Drizzle provider values: "pg" (PostgreSQL), "mysql" (MySQL), "sqlite" (SQLite). Must match the driver used.
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:
- If
secondaryStoragedefined → sessions go there (not DB) - Set
session.storeSessionInDatabase: trueto also persist to DB - 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 workemailVerification.sendOnSignUp/sendOnSignIn- Auto-send triggersemailAndPassword.sendResetPassword- Password reset email handler
Security
In advanced:
useSecureCookies- Force HTTPS cookiesdisableCSRFCheck- ⚠️ Security riskdisableOriginCheck- ⚠️ Security riskcrossSubDomainCookies.enabled- Share cookies across subdomainsipAddress.ipAddressHeaders- Custom IP headers for proxiesdatabase.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: `
Câu hỏi thường gặp
Cần những biến môi trường nào?
Cần BETTER_AUTH_SECRET và BETTER_AUTH_URL, và skill chỉ cách tạo một bí mật ngẫu nhiên đủ mạnh.
Skill hỗ trợ những công cụ cơ sở dữ liệu nào?
Nó bao quát bộ chuyển đổi tích hợp sẵn, Drizzle và Prisma.
Làm sao kiểm tra thiết lập đã hoạt động?
Nó gọi route kiểm tra sức khỏe của auth, và route này phải trả về trạng thái ok.
Chi tiết
Mô tả gốc của tác giả
Configure Better Auth server and client, set up database adapters, manage sessions, add plugins, and handle environment variables. Use when users mention Better Auth, betterauth, auth.ts, or need to set up TypeScript authentication with email/password, OAuth, or plugin configuration.
repo: trycompai/crm
Độ phổ biến
- Sao GitHub
- 12k
- Vị trí xếp hạng
- #11509
- Giấy phép
- MIT
- Cập nhật
- 1/11/2026
Bình luận
- …
Thêm skill từ kho mã này
ai-elements
12kGiúp agent của bạn xây dựng giao diện chat AI với các thành phần có sẵn cho hội thoại, tin nhắn, hiển thị công cụ và ô nhập prompt.
ai-sdk
12kGiúp agent của bạn xây dựng tính năng AI với Vercel AI SDK, gồm tạo văn bản, truyền phát, gọi công cụ và agent.
better-accessibility
12kGiúp agent của bạn làm giao diện dùng được bằng bàn phím và trình đọc màn hình, bao gồm focus, nhãn, ARIA và biểu mẫu.
better-colors
12kGiúp agent của bạn chuyển đổi, chọn và kiểm tra màu cho giao diện web, gồm bảng màu OKLCH, độ tương phản và chế độ tối.
Skill tương tự
reverse-engineer-anything
422kGiúp agent của bạn xem bên trong các app và package đã phát hành để giải thích tính năng, so sánh phiên bản hoặc hướng dẫn dựng lại bằng công cụ REA.
1password
394kGiúp agent của bạn cài đặt CLI của 1Password, đăng nhập, và đọc hoặc đưa thông tin bí mật vào mà không in giá trị ra cuộc trò chuyện.
healthcheck
394kGiúp agent của bạn rà soát bảo mật máy tính hoặc máy chủ đang chạy OpenClaw, như SSH, tường lửa, cập nhật và sao lưu, rồi đề xuất cách sửa an toàn.