🔐 Vibe Auth Kit

Build Your Own Clerk-Like Authentication System

Production-ready guide to implementing secure, modern authentication with Auth.js, PostgreSQL, and modern tooling

Why Auth is Now Vibeable

For years, authentication was relegated to third-party providers like Clerk, Auth0, or Firebase. But the game has changed. Today, building your own auth system is:

🚀 Mature Ecosystem

Auth.js (next-auth) v5 is production-ready and battle-tested across thousands of projects. The patterns are well-documented and stable.

🎯 Well-Documented Patterns

Email/password, magic links, OAuth flows, and role-based access are no longer bleeding-edge. Standard implementations exist and work reliably.

📊 Your Data, Your Rules

Self-hosting means complete ownership of user data, audit logs, and authentication flows. No vendor lock-in, no surprise pricing tiers.

💰 Cost Effective

Clerk's free tier ends at 10k monthly active users, then $25/user/month. Hosting your own costs a fraction of that at scale.

🔧 Customization Freedom

Want custom flows, branded emails, or specific business logic? You control every aspect without fighting a platform's constraints.

⚡ Performance

No external API calls for session validation. Auth checks run locally and instantly, improving user experience.

Recommended Tech Stack

Auth.js (Next.js)

authjs.dev

Open-source authentication solution for Next.js. Handles sessions, JWT, OAuth, and email providers out of the box.

Why: Industry standard, minimal setup, excellent documentation.

PostgreSQL + Prisma

PostgreSQL for data, Prisma ORM for type-safe database access.

Why: Reliable, scalable, great TypeScript support, no database migrations headaches.

Resend

resend.com

Modern email API designed for developers. Handles transactional emails and templating.

Why: Simple API, React email components, built by makers.

Arctic

Lightweight OAuth 2.0 library for handling Google, GitHub, Discord, etc.

Why: Zero dependencies, minimal, handles all major providers.

bcrypt / Argon2

Password hashing libraries for secure storage.

Why: Industry-standard, battle-tested, resistant to modern attacks.

TypeScript

Type-safe development ensures fewer runtime errors in auth logic.

Why: Catches errors at compile-time, improves security.

Production-Ready Implementation Prompt

Use this prompt with Claude, ChatGPT, or your preferred AI to generate production-grade auth code:

📋 Copy-Paste Prompt (600+ words)

You are an expert backend engineer specializing in secure authentication systems. I need you to help me build a production-ready authentication system for a Next.js application using Auth.js v5, PostgreSQL, Prisma, and TypeScript. ## Requirements ### 1. Core Authentication Flows Build the following authentication flows: **Email & Password Authentication** - User signup with email, password, and profile information - Password validation (minimum 12 characters, uppercase, lowercase, number, special char) - Password hashing using bcrypt (cost factor: 12) or Argon2 - Login with email and password - Automatic session creation upon successful login - Account lockout after 5 failed attempts (15-minute cooldown) **Magic Link Authentication** - Passwordless login via email magic links - 15-minute token expiration - Tokens stored in database with hash - One-time use enforcement - Resend email integration for sending **OAuth Providers (Google & GitHub)** - OAuth 2.0 implementation using Arctic - User linking if email matches existing account - First-time signup auto-population of profile - Graceful fallback to email/password if OAuth fails **Email Verification Flow** - Send verification email on signup (unless using OAuth) - Verification token with 24-hour expiration - Prevent login until verified (optional: grace period) - Resend verification email functionality **Password Reset** - Forgot password flow via email - Reset tokens with 1-hour expiration - New password must be different from last 3 passwords - Send confirmation email after reset - Invalidate all active sessions after password reset ### 2. Session Management - JWT-based sessions with HttpOnly, Secure, SameSite cookies - 30-day session expiration (configurable) - Refresh token rotation every 24 hours - Session invalidation on logout - Multiple session tracking per user (device management optional) - Rate-limited session endpoints (10 requests per minute per user) ### 3. Role-Based Access Control (RBAC) Create a basic RBAC system with roles: user, moderator, admin - Middleware to check user roles before route access - Permission matrix for CRUD operations - Database schema supporting role assignments - Audit logging of permission changes ### 4. Security Checklist (MUST IMPLEMENT) - CSRF protection via tokens - Rate limiting on login (5 attempts per 15 minutes) - Rate limiting on signup (3 per hour per IP) - Rate limiting on password reset (3 per hour per email) - Secure password storage with bcrypt/Argon2 - HTTPS only in production - HttpOnly, Secure, SameSite=Strict cookies - Session CSRF tokens - Input validation and sanitization - SQL injection prevention via ORM - XSS protection in email templates - No password hints or recovery questions - Account enumeration prevention ### 5. Database Schema (Prisma) Create comprehensive schema including: - User model (id, email, password, name, emailVerified, createdAt, updatedAt) - Session model (id, userId, token, expiresAt, createdAt) - VerificationToken model (email, token, expires, type) - Account model (for OAuth linking) - Role model (id, name, permissions) - UserRole model (userId, roleId) - AuditLog model (userId, action, resource, timestamp, details) ### 6. API Endpoints (Next.js API routes or App Router) - POST /auth/signup - Register new user - POST /auth/login - Email/password login - POST /auth/logout - Destroy session - POST /auth/magic-link - Request magic link - GET /auth/magic-link/verify?token=X - Verify magic link - POST /auth/oauth/[provider] - OAuth flow initiation - GET /auth/oauth/[provider]/callback - OAuth callback - POST /auth/email/verify - Request email verification - GET /auth/email/verify?token=X - Verify email - POST /auth/password/forgot - Initiate password reset - POST /auth/password/reset - Complete password reset - GET /auth/session - Get current session - POST /auth/session/logout-all - Logout from all devices - GET /auth/user/profile - Get user profile - PATCH /auth/user/profile - Update profile - GET /api/admin/users - List users (admin only) - PATCH /api/admin/users/[id]/role - Change user role (admin only) ### 7. Email Templates Design professional email templates using React Email components: - Welcome email with email verification link - Magic link login email - Password reset confirmation - Email change confirmation - Suspicious login alert ### 8. Environment Configuration List all required environment variables: - DATABASE_URL - NEXTAUTH_SECRET - NEXTAUTH_URL - GOOGLE_CLIENT_ID - GOOGLE_CLIENT_SECRET - GITHUB_CLIENT_ID - GITHUB_CLIENT_SECRET - RESEND_API_KEY ### 9. Testing Strategy Provide unit tests for: - Password hashing and verification - Email validation regex - Session creation and validation - Rate limiting logic - Role-based access control - CSRF token validation ### 10. Deployment Checklist - Environment variables secured in production - Database backups configured - Rate limiting properly tuned for scale - Session cleanup cron job (remove expired sessions daily) - Error logging configured - Performance monitoring ## Output Format Provide: 1. Complete Prisma schema 2. Core middleware/utilities for auth 3. All API endpoints with full implementation 4. Security utilities (hashing, rate limiting, CSRF) 5. Email templates using React Email 6. TypeScript types for auth objects 7. Error handling patterns 8. Environment setup guide Make it production-ready, secure, and maintainable. Follow Next.js best practices and use TypeScript throughout.

✅ What This Prompt Covers

🔒 Security Checklist

Use this to audit your authentication system before production:

📅 2-Week Implementation Timeline

Week 1: Core Auth Flows

Day 1-2: Setup & Database

  • Initialize Next.js + TypeScript project
  • Set up PostgreSQL database locally
  • Configure Prisma with schema (User, Session, VerificationToken)
  • Environment variables setup

Day 3-4: Email & Password Authentication

  • Implement bcrypt password hashing utility
  • Build signup endpoint with validation
  • Build login endpoint with rate limiting
  • Create session management system
  • Build logout functionality

Day 5: Email Verification & Reset

  • Set up Resend integration
  • Email verification flow (request + verify endpoints)
  • Password reset flow (forgot + reset endpoints)
  • Email templates

Day 6-7: Magic Link & Testing

  • Magic link authentication endpoint
  • Unit tests for core flows
  • Manual testing in Postman/Insomnia
  • Security audit checklist (first pass)
Week 2: Advanced Features & Polish

Day 8-9: OAuth Integration

  • Set up OAuth apps (Google, GitHub)
  • Arctic configuration
  • Build OAuth initiation endpoints
  • Build callback handlers with account linking
  • Test both providers

Day 10: Role-Based Access Control

  • Add Role & UserRole models to Prisma
  • Create role middleware
  • Admin endpoint to assign roles
  • Permission matrix setup

Day 11: Polish & Error Handling

  • Comprehensive error handling across all endpoints
  • User-friendly error messages
  • Logging and monitoring setup
  • TypeScript type cleanup

Day 12-13: Integration Testing & Docs

  • End-to-end testing of all flows
  • Security testing (rate limits, CSRF, injection)
  • Write API documentation
  • Deployment guide

Day 14: Final Security Audit & Deploy

  • Full security checklist review
  • Code review for best practices
  • Staging environment test
  • Production deployment
  • Monitor logs and performance

🚀 Open Source Starting Points

Core Libraries & Frameworks

Reference Implementations

Email & OAuth

Database & ORM

Security Libraries

Deployment & Infrastructure

🎯 When to Build vs. Buy

Use this matrix to decide whether to build your own auth or use a platform:

Factor
Build Your Own ✅
Buy a Platform ❌
User Count
Under 100k MAU (Monthly Active Users)
Over 500k MAU where compliance becomes complex
Customization
Need custom auth flows, branding, or business logic
Happy with standard auth patterns
Data Ownership
Must control user data, audit logs, compliance
Comfortable with third-party data handling
Budget
Under $500/month for infrastructure
Can afford $25-100/user/month at scale
Engineering
1-2 engineers, 2-4 weeks of time available
No engineering capacity for custom auth
Compliance
GDPR/CCPA compliance is easier to prove (self-hosted)
Need SOC2, HIPAA, or enterprise SLA guarantees
Integrations
Can write custom OAuth provider integrations
Need out-of-the-box enterprise SSO (SAML, OpenID Connect)
Maintenance
Willing to maintain and update dependencies
Prefer no-maintenance, fully managed solution
Support
Can debug issues using open-source community
Need 24/7 enterprise support

The Hybrid Approach

🌉 Use Clerk/Auth0 Initially, Migrate Later

Start with a managed provider to validate your product market fit quickly. Once you have PMF and a larger user base, migrate to self-hosted auth using this kit. The Auth.js ecosystem makes this migration painless.

Benefit: Get to market fast, reduce initial engineering overhead, then own your auth when it becomes economically viable.

🚀 Getting Started Now

Step 1: Prepare Your Project

npm create next-app@latest my-auth-app --typescript cd my-auth-app npm install @auth/core @auth/prisma-adapter prisma @prisma/client

Step 2: Set Up Database

npm install -D @prisma/cli npx prisma init # Set DATABASE_URL in .env.local npx prisma migrate dev --name init

Step 3: Use the Prompt

Copy the prompt above and paste it into Claude/ChatGPT with your project details. You'll get complete, production-ready code.

Step 4: Implement Security

Walk through the security checklist and audit every implementation against it.

Step 5: Test & Deploy

Write tests, deploy to staging, then production. Monitor logs for issues.

💡 Pro Tip: Use this approach for your first implementation: Email/password + magic link (Week 1), then add OAuth (Week 2) once core flows are solid.