--- name: ck-better-auth description: > Implements authentication and authorization using Better Auth library patterns. Activate when user says 'add authentication', 'implement login', 'set up auth', 'user sessions', 'OAuth integration', or 'role-based access control'. Accepts framework context (Next.js, Express, etc.) and provider requirements. --- ## Overview Scaffolds and implements authentication flows using Better Auth (better-auth.com), covering session management, OAuth providers, email/password auth, and RBAC patterns. ## When to Use - Setting up authentication from scratch in a web application - Adding OAuth providers (GitHub, Google, Discord, etc.) - Implementing session-based or JWT authentication - Adding role-based or permission-based access control - Securing API routes and server-side pages ## Don't Use When - Project already has a working auth system and only needs minor fixes - Building a purely public API with no user accounts - Using a managed auth service like Clerk or Auth0 (those have their own SDKs) - Mobile-only app requiring native auth flows ## Steps / Instructions ### 1. Install Better Auth ```bash npm install better-auth ``` ### 2. Configure Auth Instance ```typescript // lib/auth.ts import { betterAuth } from 'better-auth'; import { prismaAdapter } from 'better-auth/adapters/prisma'; import { prisma } from './prisma'; export const auth = betterAuth({ database: prismaAdapter(prisma, { provider: 'postgresql' }), emailAndPassword: { enabled: true }, socialProviders: { github: { clientId: process.env.GITHUB_CLIENT_ID!, clientSecret: process.env.GITHUB_CLIENT_SECRET!, }, google: { clientId: process.env.GOOGLE_CLIENT_ID!, clientSecret: process.env.GOOGLE_CLIENT_SECRET!, }, }, session: { expiresIn: 60 * 60 * 24 * 7, // 7 days updateAge: 60 * 60 * 24, // refresh if older than 1 day }, }); ``` ### 3. Set Up API Route (Next.js) ```typescript // app/api/auth/[...all]/route.ts import { auth } from '@/lib/auth'; import { toNextJsHandler } from 'better-auth/next-js'; export const { GET, POST } = toNextJsHandler(auth); ``` ### 4. Create Auth Client ```typescript // lib/auth-client.ts import { createAuthClient } from 'better-auth/react'; export const authClient = createAuthClient({ baseURL: process.env.NEXT_PUBLIC_APP_URL, }); export const { signIn, signOut, signUp, useSession } = authClient; ``` ### 5. Protect Routes (Next.js Middleware) ```typescript // middleware.ts import { auth } from '@/lib/auth'; import { NextRequest, NextResponse } from 'next/server'; export async function middleware(request: NextRequest) { const session = await auth.api.getSession({ headers: request.headers, }); if (!session && request.nextUrl.pathname.startsWith('/dashboard')) { return NextResponse.redirect(new URL('/login', request.url)); } return NextResponse.next(); } export const config = { matcher: ['/dashboard/:path*', '/settings/:path*'], }; ``` ### 6. Add RBAC (Optional) ```typescript import { betterAuth } from 'better-auth'; import { rbac } from 'better-auth/plugins'; export const auth = betterAuth({ // ...base config plugins: [ rbac({ roles: { admin: { permissions: ['read', 'write', 'delete'] }, user: { permissions: ['read'] }, }, }), ], }); ``` ### 7. Database Schema Migration Run Better Auth CLI to generate schema: ```bash npx better-auth generate npx prisma migrate dev --name add-auth-tables ``` ### 8. Environment Variables Required ```bash # .env (never commit this file) BETTER_AUTH_SECRET= BETTER_AUTH_URL=http://localhost:3000 GITHUB_CLIENT_ID=... GITHUB_CLIENT_SECRET=... GOOGLE_CLIENT_ID=... GOOGLE_CLIENT_SECRET=... ``` ## Notes - Always generate `BETTER_AUTH_SECRET` with a cryptographically secure method - Never expose client secrets in frontend code or version control - Use HTTPS in production — sessions over HTTP are insecure - Test OAuth flows with provider sandbox/test apps before production