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:
- Go to Google Cloud Console
- Create a project or select existing
- Enable "Google+ API"
- Go to "Credentials" → "Create Credentials" → "OAuth client ID"
- Configure OAuth consent screen if prompted
- Set redirect URI:
http://localhost:3000/api/auth/callback/google(and production URL) - Copy Client ID and Client Secret
For GitHub OAuth:
- Go to GitHub → Settings → Developer settings → OAuth Apps
- Click "New OAuth App"
- Set Authorization callback URL:
http://localhost:3000/api/auth/callback/github - 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_URLmust match your app URL exactlyNEXTAUTH_SECRETis 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
- Restart your dev server:
npm run dev - Navigate to
http://localhost:3000/api/auth/signin(NextAuth sign-in page) - Try signing in with your configured provider
- Verify you're redirected to the callback URL
- Check that session is created (verify in database or check cookies)
- Test protected routes to ensure authentication works
Troubleshooting:
- If redirect fails, verify
NEXTAUTH_URLmatches your app URL exactly - Check OAuth redirect URIs match in both NextAuth config and OAuth provider
- Verify
NEXTAUTH_SECRETis set correctly - Check browser console and server logs for detailed errors
- Ensure database is properly configured for session storage