Authentication & Authorization Setup

Type: Execution Recipe Confidence: 0.91 Sources: 7 Verified: 2026-03-12

Purpose

This recipe implements a complete authentication system for an MVP — covering provider selection, configuration, social login (Google, GitHub), magic links, email/password, protected routes, and role-based authorization. Working auth flow within 60 minutes. [src1]

Prerequisites

Constraints

Tool Selection Decision

Which auth provider?
├── Next.js SaaS AND want drop-in UI AND < 10K users
│   └── PROVIDER A: Clerk — fastest setup, $0 for 10K MAU
├── Already using Supabase AND want bundled auth
│   └── PROVIDER B: Supabase Auth — integrated with RLS, $0 for 50K MAU
├── Need enterprise SSO/SAML AND HIPAA
│   └── PROVIDER C: Auth0 — most compliant, $0 for 25K MAU
└── Google ecosystem AND need phone auth
    └── PROVIDER D: Firebase Auth — phone OTP, $0 for 50K MAU
ProviderFree MAUCost AfterSetup TimePre-built UISocial LoginMagic Link
Clerk10,000$0.02/MAU15 minYes (excellent)YesYes
Supabase Auth50,000$0.00325/MAU30 minNo (build own)YesYes
Auth025,000$0.07/MAU45 minRedirect-basedYesYes
Firebase Auth50,000SMS pricing30 minFirebaseUIYesEmail link

Execution Flow

Step 1: Create Provider Account and Get Credentials

Duration: 5 minutes · Tool: Provider dashboard

Sign up at your chosen provider. Copy API keys to .env.local. Enable auth methods (email, social, magic link) in the dashboard. For social login, paste Google/GitHub OAuth Client ID and Secret. [src2] [src1]

Verify: Environment variables set and provider dashboard shows application. · If failed: Check URL format (no trailing slash) and key types.

Step 2: Install Dependencies and Configure Provider

Duration: 5-10 minutes · Tool: CLI + code editor

Clerk: Install @clerk/nextjs, wrap app with ClerkProvider, add middleware with clerkMiddleware. [src2]

Supabase: Install @supabase/ssr, create browser and server clients, add middleware for session refresh and route protection. [src1]

Verify: No build errors; app starts without auth console errors. · If failed: Check env var names and middleware placement.

Step 3: Build Authentication Pages

Duration: 10-15 minutes · Tool: Code editor

Clerk: Use pre-built <SignIn /> and <SignUp /> components with catch-all routes. [src2]

Supabase: Build custom forms calling supabase.auth.signInWithPassword(), signInWithOtp(), and signInWithOAuth(). Create OAuth callback route handler. [src1] [src5]

Verify: Signup, login, social login, and magic link all work. · If failed: Check OAuth redirect URIs and callback route.

Step 4: Add Role-Based Authorization

Duration: 10 minutes · Tool: Code editor + provider dashboard

Clerk: Enable Organizations, use orgRole from auth() for access control.

Supabase: Add role column to profiles table, create RLS policies checking role, build server-side requireRole() helper.

Verify: Admin users access admin routes; non-admins see access denied. · If failed: Check RLS policies include role checks.

Step 5: Configure Production Settings

Duration: 10 minutes · Tool: Provider dashboard + DNS

Add production domain to auth provider. Update OAuth redirect URIs for production. Configure custom SMTP for magic links. Set environment variables in hosting platform (Vercel).

Verify: Auth works on production URL; emails arrive in inbox. · If failed: Verify production domain in all OAuth providers; check SMTP configuration.

Output Schema

{
  "output_type": "authentication_system",
  "format": "code + configured provider",
  "columns": [
    {"name": "auth_provider", "type": "string", "description": "Provider used", "required": true},
    {"name": "auth_methods", "type": "string", "description": "Enabled methods", "required": true},
    {"name": "protected_routes", "type": "string", "description": "Routes requiring auth", "required": true},
    {"name": "roles_defined", "type": "string", "description": "User roles and permissions", "required": false},
    {"name": "oauth_providers", "type": "string", "description": "Social login providers", "required": false}
  ],
  "expected_row_count": "1",
  "sort_order": "N/A",
  "deduplication_key": "auth_provider"
}

Quality Benchmarks

Quality MetricMinimum AcceptableGoodExcellent
Auth flow completenessSignup + login + logout+ Social + magic link+ Phone + MFA
Session securityCookie-based sessions+ httpOnly + secure flags+ CSRF + token rotation
Protected routes/dashboard requires auth+ Role-based guards+ API route protection
Error UXGeneric error messages+ Specific messages+ Inline validation
Time to authenticate< 5 seconds< 3 seconds< 1 second

If below minimum: Verify middleware protects routes. Check session cookies have httpOnly and secure flags.

Error Handling

ErrorLikely CauseRecovery Action
Invalid redirect URIMismatch in provider dashboardCopy exact URI from error to provider dashboard
CORS error on callbackMissing domain in allowed originsAdd domain to provider's CORS settings
Magic link not receivedDefault SMTP flagged as spamConfigure custom SMTP via Resend or SendGrid
Session not persistingCookies not set in middlewareVerify middleware runs on all routes
401 on protected APIMissing auth header or expired tokenCheck middleware forwards cookies; verify token refresh

Cost Breakdown

ProviderFree TierAt 10K MAUAt 50K MAUAt 100K MAU
Clerk$0 (10K)$0$800/mo$1,800/mo
Supabase Auth$0 (50K)$0$0$162.50/mo
Auth0$0 (25K)$0$1,750/mo$5,250/mo
Firebase Auth$0 (50K)$0$0SMS costs only

Anti-Patterns

Wrong: Building custom authentication from scratch

Custom auth takes 2-4 weeks and is the #1 source of MVP security vulnerabilities. [src6]

Correct: Use a managed auth provider from day one

Pick Clerk for fastest setup, Supabase for best value, Auth0 for enterprise compliance.

Wrong: Storing sessions in localStorage

Vulnerable to XSS attacks — a single vulnerability compromises all sessions. [src6]

Correct: Use httpOnly cookies for session storage

Clerk and Supabase Auth use httpOnly cookies by default with their SSR packages.

Wrong: Using test OAuth credentials in production

Test credentials show "unverified app" warnings and have rate limits. [src4]

Correct: Register your own OAuth apps

Create production credentials with your app name, logo, and privacy policy URL.

When This Matters

Use this recipe when a developer needs to add authentication to an existing MVP project. Requires a project scaffold. Covers provider setup, social login, magic links, protected routes, and role-based authorization — not onboarding flows or profile management UI.

Related Units