Skill for creating auth layers in TypeScript/JavaScript apps using Better Auth.
Add this skill
npx mdskills install better-auth/create-authComprehensive two-phase workflow with intelligent project scanning and structured planning before implementation
1---2name: create-auth-skill3description: Skill for creating auth layers in TypeScript/JavaScript apps using Better Auth.4---56# Create Auth Skill78Guide for adding authentication to TypeScript/JavaScript applications using Better Auth.910**For code examples and syntax, see [better-auth.com/docs](https://better-auth.com/docs).**1112---1314## Phase 1: Planning (REQUIRED before implementation)1516Before writing any code, gather requirements by scanning the project and asking the user structured questions. This ensures the implementation matches their needs.1718### Step 1: Scan the project1920Analyze the codebase to auto-detect:21- **Framework** — Look for `next.config`, `svelte.config`, `nuxt.config`, `astro.config`, `vite.config`, or Express/Hono entry files.22- **Database/ORM** — Look for `prisma/schema.prisma`, `drizzle.config`, `package.json` deps (`pg`, `mysql2`, `better-sqlite3`, `mongoose`, `mongodb`).23- **Existing auth** — Look for existing auth libraries (`next-auth`, `lucia`, `clerk`, `supabase/auth`, `firebase/auth`) in `package.json` or imports.24- **Package manager** — Check for `pnpm-lock.yaml`, `yarn.lock`, `bun.lockb`, or `package-lock.json`.2526Use what you find to pre-fill defaults and skip questions you can already answer.2728### Step 2: Ask planning questions2930Use the `AskQuestion` tool to ask the user **all applicable questions in a single call**. Skip any question you already have a confident answer for from the scan. Group them under a title like "Auth Setup Planning".3132**Questions to ask:**33341. **Project type** (skip if detected)35 - Prompt: "What type of project is this?"36 - Options: New project from scratch | Adding auth to existing project | Migrating from another auth library37382. **Framework** (skip if detected)39 - Prompt: "Which framework are you using?"40 - Options: Next.js (App Router) | Next.js (Pages Router) | SvelteKit | Nuxt | Astro | Express | Hono | SolidStart | Other41423. **Database & ORM** (skip if detected)43 - Prompt: "Which database setup will you use?"44 - Options: PostgreSQL (Prisma) | PostgreSQL (Drizzle) | PostgreSQL (pg driver) | MySQL (Prisma) | MySQL (Drizzle) | MySQL (mysql2 driver) | SQLite (Prisma) | SQLite (Drizzle) | SQLite (better-sqlite3 driver) | MongoDB (Mongoose) | MongoDB (native driver)45464. **Authentication methods** (always ask, allow multiple)47 - Prompt: "Which sign-in methods do you need?"48 - Options: Email & password | Social OAuth (Google, GitHub, etc.) | Magic link (passwordless email) | Passkey (WebAuthn) | Phone number49 - `allow_multiple: true`50515. **Social providers** (only if they selected Social OAuth above — ask in a follow-up call)52 - Prompt: "Which social providers do you need?"53 - Options: Google | GitHub | Apple | Microsoft | Discord | Twitter/X54 - `allow_multiple: true`55566. **Email verification** (only if Email & password was selected above — ask in a follow-up call)57 - Prompt: "Do you want to require email verification?"58 - Options: Yes | No59607. **Email provider** (only if email verification is Yes, or if Password reset is selected in features — ask in a follow-up call)61 - Prompt: "How do you want to send emails?"62 - Options: Resend | Mock it for now (console.log)63648. **Features & plugins** (always ask, allow multiple)65 - Prompt: "Which additional features do you need?"66 - Options: Two-factor authentication (2FA) | Organizations / teams | Admin dashboard | API bearer tokens | Password reset | None of these67 - `allow_multiple: true`68699. **Auth pages** (always ask, allow multiple — pre-select based on earlier answers)70 - Prompt: "Which auth pages do you need?"71 - Options vary based on previous answers:72 - Always available: Sign in | Sign up73 - If Email & password selected: Forgot password | Reset password74 - If email verification enabled: Email verification75 - `allow_multiple: true`767710. **Auth UI style** (always ask)78 - Prompt: "What style do you want for the auth pages? Pick one or describe your own."79 - Options: Minimal & clean | Centered card with background | Split layout (form + hero image) | Floating / glassmorphism | Other (I'll describe)8081### Step 3: Summarize the plan8283After collecting answers, present a concise implementation plan as a markdown checklist. Example:8485```86## Auth Implementation Plan8788- **Framework:** Next.js (App Router)89- **Database:** PostgreSQL via Prisma90- **Auth methods:** Email/password, Google OAuth, GitHub OAuth91- **Plugins:** 2FA, Organizations, Email verification92- **UI:** Custom forms9394### Steps951. Install `better-auth` and `@better-auth/cli`962. Create `lib/auth.ts` with server config973. Create `lib/auth-client.ts` with React client984. Set up route handler at `app/api/auth/[...all]/route.ts`995. Configure Prisma adapter and generate schema1006. Add Google & GitHub OAuth providers1017. Enable `twoFactor` and `organization` plugins1028. Set up email verification handler1039. Run migrations10410. Create sign-in / sign-up pages105```106107Ask the user to confirm the plan before proceeding to Phase 2.108109---110111## Phase 2: Implementation112113Only proceed here after the user confirms the plan from Phase 1.114115Follow the decision tree below, guided by the answers collected above.116117```118Is this a new/empty project?119├─ YES → New project setup120│ 1. Install better-auth (+ scoped packages per plan)121│ 2. Create auth.ts with all planned config122│ 3. Create auth-client.ts with framework client123│ 4. Set up route handler124│ 5. Set up environment variables125│ 6. Run CLI migrate/generate126│ 7. Add plugins from plan127│ 8. Create auth UI pages128│129├─ MIGRATING → Migration from existing auth130│ 1. Audit current auth for gaps131│ 2. Plan incremental migration132│ 3. Install better-auth alongside existing auth133│ 4. Migrate routes, then session logic, then UI134│ 5. Remove old auth library135│ 6. See migration guides in docs136│137└─ ADDING → Add auth to existing project138 1. Analyze project structure139 2. Install better-auth140 3. Create auth config matching plan141 4. Add route handler142 5. Run schema migrations143 6. Integrate into existing pages144 7. Add planned plugins and features145```146147At the end of implementation, guide users thoroughly on remaining next steps (e.g., setting up OAuth app credentials, deploying env vars, testing flows).148149---150151## Installation152153**Core:** `npm install better-auth`154155**Scoped packages (as needed):**156| Package | Use case |157|---------|----------|158| `@better-auth/passkey` | WebAuthn/Passkey auth |159| `@better-auth/sso` | SAML/OIDC enterprise SSO |160| `@better-auth/stripe` | Stripe payments |161| `@better-auth/scim` | SCIM user provisioning |162| `@better-auth/expo` | React Native/Expo |163164---165166## Environment Variables167168```env169BETTER_AUTH_SECRET=<32+ chars, generate with: openssl rand -base64 32>170BETTER_AUTH_URL=http://localhost:3000171DATABASE_URL=<your database connection string>172```173174Add OAuth secrets as needed: `GITHUB_CLIENT_ID`, `GITHUB_CLIENT_SECRET`, `GOOGLE_CLIENT_ID`, etc.175176---177178## Server Config (auth.ts)179180**Location:** `lib/auth.ts` or `src/lib/auth.ts`181182**Minimal config needs:**183- `database` - Connection or adapter184- `emailAndPassword: { enabled: true }` - For email/password auth185186**Standard config adds:**187- `socialProviders` - OAuth providers (google, github, etc.)188- `emailVerification.sendVerificationEmail` - Email verification handler189- `emailAndPassword.sendResetPassword` - Password reset handler190191**Full config adds:**192- `plugins` - Array of feature plugins193- `session` - Expiry, cookie cache settings194- `account.accountLinking` - Multi-provider linking195- `rateLimit` - Rate limiting config196197**Export types:** `export type Session = typeof auth.$Infer.Session`198199---200201## Client Config (auth-client.ts)202203**Import by framework:**204| Framework | Import |205|-----------|--------|206| React/Next.js | `better-auth/react` |207| Vue | `better-auth/vue` |208| Svelte | `better-auth/svelte` |209| Solid | `better-auth/solid` |210| Vanilla JS | `better-auth/client` |211212**Client plugins** go in `createAuthClient({ plugins: [...] })`.213214**Common exports:** `signIn`, `signUp`, `signOut`, `useSession`, `getSession`215216---217218## Route Handler Setup219220| Framework | File | Handler |221|-----------|------|---------|222| Next.js App Router | `app/api/auth/[...all]/route.ts` | `toNextJsHandler(auth)` → export `{ GET, POST }` |223| Next.js Pages | `pages/api/auth/[...all].ts` | `toNextJsHandler(auth)` → default export |224| Express | Any file | `app.all("/api/auth/*", toNodeHandler(auth))` |225| SvelteKit | `src/hooks.server.ts` | `svelteKitHandler(auth)` |226| SolidStart | Route file | `solidStartHandler(auth)` |227| Hono | Route file | `auth.handler(c.req.raw)` |228229**Next.js Server Components:** Add `nextCookies()` plugin to auth config.230231---232233## Database Migrations234235| Adapter | Command |236|---------|---------|237| Built-in Kysely | `npx @better-auth/cli@latest migrate` (applies directly) |238| Prisma | `npx @better-auth/cli@latest generate --output prisma/schema.prisma` then `npx prisma migrate dev` |239| Drizzle | `npx @better-auth/cli@latest generate --output src/db/auth-schema.ts` then `npx drizzle-kit push` |240241**Re-run after adding plugins.**242243---244245## Database Adapters246247| Database | Setup |248|----------|-------|249| SQLite | Pass `better-sqlite3` or `bun:sqlite` instance directly |250| PostgreSQL | Pass `pg.Pool` instance directly |251| MySQL | Pass `mysql2` pool directly |252| Prisma | `prismaAdapter(prisma, { provider: "postgresql" })` from `better-auth/adapters/prisma` |253| Drizzle | `drizzleAdapter(db, { provider: "pg" })` from `better-auth/adapters/drizzle` |254| MongoDB | `mongodbAdapter(db)` from `better-auth/adapters/mongodb` |255256---257258## Common Plugins259260| Plugin | Server Import | Client Import | Purpose |261|--------|---------------|---------------|---------|262| `twoFactor` | `better-auth/plugins` | `twoFactorClient` | 2FA with TOTP/OTP |263| `organization` | `better-auth/plugins` | `organizationClient` | Teams/orgs |264| `admin` | `better-auth/plugins` | `adminClient` | User management |265| `bearer` | `better-auth/plugins` | - | API token auth |266| `openAPI` | `better-auth/plugins` | - | API docs |267| `passkey` | `@better-auth/passkey` | `passkeyClient` | WebAuthn |268| `sso` | `@better-auth/sso` | - | Enterprise SSO |269270**Plugin pattern:** Server plugin + client plugin + run migrations.271272---273274## Auth UI Implementation275276**Sign in flow:**2771. `signIn.email({ email, password })` or `signIn.social({ provider, callbackURL })`2782. Handle `error` in response2793. Redirect on success280281**Session check (client):** `useSession()` hook returns `{ data: session, isPending }`282283**Session check (server):** `auth.api.getSession({ headers: await headers() })`284285**Protected routes:** Check session, redirect to `/sign-in` if null.286287---288289## Security Checklist290291- [ ] `BETTER_AUTH_SECRET` set (32+ chars)292- [ ] `advanced.useSecureCookies: true` in production293- [ ] `trustedOrigins` configured294- [ ] Rate limits enabled295- [ ] Email verification enabled296- [ ] Password reset implemented297- [ ] 2FA for sensitive apps298- [ ] CSRF protection NOT disabled299- [ ] `account.accountLinking` reviewed300301---302303## Troubleshooting304305| Issue | Fix |306|-------|-----|307| "Secret not set" | Add `BETTER_AUTH_SECRET` env var |308| "Invalid Origin" | Add domain to `trustedOrigins` |309| Cookies not setting | Check `baseURL` matches domain; enable secure cookies in prod |310| OAuth callback errors | Verify redirect URIs in provider dashboard |311| Type errors after adding plugin | Re-run CLI generate/migrate |312313---314315## Resources316317- [Docs](https://better-auth.com/docs)318- [Examples](https://github.com/better-auth/examples)319- [Plugins](https://better-auth.com/docs/concepts/plugins)320- [CLI](https://better-auth.com/docs/concepts/cli)321- [Migration Guides](https://better-auth.com/docs/guides)322
Full transparency — inspect the skill content before installing.