NextAuth
Last updated December 18, 2025

Overview

NextAuth.js (Auth.js) is a popular authentication library for Next.js. It supports email/password, OAuth providers (Google, GitHub, etc.), and database sessions. The scaffold uses NextAuth v5 (Auth.js) with adapters for your database.

Generate NEXTAUTH_SECRET

Generate a secure random secret for NextAuth. This is used to encrypt sessions and tokens.

Option 1: Using OpenSSL (recommended)

openssl rand -base64 32

Option 2: Using Node.js

node -e "console.log(require('crypto').randomBytes(32).toString('base64'))"

Copy the generated secret - you'll add it to your .env.local file.

Configure Providers

For Google OAuth:

  1. Go to Google Cloud Console
  2. Create a project or select existing
  3. Enable "Google+ API"
  4. Go to "Credentials" → "Create Credentials" → "OAuth client ID"
  5. Configure OAuth consent screen if prompted
  6. Set redirect URI: http://localhost:3000/api/auth/callback/google (and production URL)
  7. Copy Client ID and Client Secret

For GitHub OAuth:

  1. Go to GitHub → Settings → Developer settings → OAuth Apps
  2. Click "New OAuth App"
  3. Set Authorization callback URL: http://localhost:3000/api/auth/callback/github
  4. Copy Client ID and Client Secret

For Email Provider: NextAuth supports magic links via email. You'll need to configure an email service (Resend, SendGrid, etc.) in your NextAuth configuration.

Environment Variables

Add these variables to your .env.local file:

# NextAuth
NEXTAUTH_URL="http://localhost:3000"
NEXTAUTH_SECRET="your-generated-secret-from-step-1"

# Google OAuth (if using Google provider)
GOOGLE_CLIENT_ID="your-google-client-id.apps.googleusercontent.com"
GOOGLE_CLIENT_SECRET="your-google-client-secret"

# GitHub OAuth (if using GitHub provider)
GITHUB_CLIENT_ID="your-github-client-id"
GITHUB_CLIENT_SECRET="your-github-client-secret"

# Database (required for sessions)
DATABASE_URL="your-database-connection-string"

Important:

  • NEXTAUTH_URL must match your app URL exactly
  • NEXTAUTH_SECRET is required - use the secret you generated
  • OAuth provider credentials are only needed if you're using those providers
  • Database URL is required for session storage

Testing

  1. Restart your dev server: npm run dev
  2. Navigate to http://localhost:3000/api/auth/signin (NextAuth sign-in page)
  3. Try signing in with your configured provider
  4. Verify you're redirected to the callback URL
  5. Check that session is created (verify in database or check cookies)
  6. Test protected routes to ensure authentication works

Troubleshooting:

  • If redirect fails, verify NEXTAUTH_URL matches your app URL exactly
  • Check OAuth redirect URIs match in both NextAuth config and OAuth provider
  • Verify NEXTAUTH_SECRET is set correctly
  • Check browser console and server logs for detailed errors
  • Ensure database is properly configured for session storage