better-auth-best-practices
하는 일
Better Auth의 서버, 클라이언트, 데이터베이스 어댑터, 세션, 환경 변수를 설정하도록 AI 에이전트를 안내합니다. TypeScript 프로젝트에 인증을 추가하는 개발자를 위한 스킬입니다.
사용하는 경우
- ✓TypeScript 앱에 이메일과 비밀번호 또는 OAuth 로그인을 추가할 때.
- ✓Better Auth의 auth.ts 파일, 데이터베이스 어댑터, 라우트 핸들러를 설정할 때.
- ✓Better Auth 플러그인을 추가하거나 환경 변수를 고쳐야 할 때.
스킬 링크
https://github.com/trycompai/crm/blob/release/.agents/skills/better-auth-best-practices/SKILL.md복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.
사용 방법
가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.
바로 붙여넣을 수 있는 메시지
Claude Code, Codex, Cursor용입니다. 프로젝트 폴더에서 실행하면 스킬이 설치됩니다.
SKILL.md를 다운로드해 에이전트의 스킬 폴더에 넣으세요.
AI에게 요청하는 예시
“내 TypeScript 앱에 이메일과 비밀번호 로그인이 되도록 Better Auth를 설정해 주세요.”
매주 새 스킬 5개. 읽는 데 1분.
작동 방식
AI는 패키지를 설치하고, 비밀 값과 URL 변수를 설정한 뒤, 인증 구성을 만들고, 데이터베이스 마이그레이션을 실행하며 상태 점검 엔드포인트를 확인합니다.
기술 내용 (원본 SKILL.md)
작성자의 영어 원문을 GitHub에서 그대로 가져왔습니다.
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: `
자주 묻는 질문
어떤 환경 변수가 필요한가요?
BETTER_AUTH_SECRET과 BETTER_AUTH_URL이 필요하며, 강력한 무작위 비밀 값을 만드는 방법도 보여 줍니다.
어떤 데이터베이스 도구를 지원하나요?
기본 어댑터, Drizzle, Prisma를 다룹니다.
설정이 제대로 되었는지 어떻게 확인하나요?
인증 상태 확인 라우트를 호출하며, 이때 ok 상태가 반환되어야 합니다.
상세 정보
작성자의 원본 설명
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
인기도
- GitHub 스타
- 12k
- 순위
- #11509
- 라이선스
- MIT
- 업데이트
- 2026. 11. 1.
댓글
- …
이 저장소의 다른 스킬
ai-elements
12k에이전트가 대화, 메시지, 도구 표시, 프롬프트 입력을 위한 기성 컴포넌트로 AI 채팅 화면을 만들도록 돕습니다.
ai-sdk
12k에이전트가 Vercel AI SDK로 텍스트 생성, 스트리밍, 도구 호출, 에이전트를 포함한 AI 기능을 만들도록 돕습니다.
better-accessibility
12k에이전트가 키보드와 스크린 리더로도 사용할 수 있도록 인터페이스를 만들며, 포커스, 레이블, ARIA, 양식을 다루도록 돕습니다.
better-colors
12k에이전트가 웹 인터페이스의 색상을 변환하고, 고르고, 확인하도록 돕습니다. OKLCH 팔레트, 대비, 다크 모드를 포함합니다.