authjs-skills
Auth.js v5 setup for Next.js authentication including Google OAuth, credentials provider, environment configuration, and core API integration
By gocallum · 750 installs
npx skills add gocallum/nextjs16-agent-skills --skill authjs-skills
Source repository · Upstream listing
Links
Getting Started: https://authjs.dev/getting started/installation?framework=Next.js
Migrating to v5: https://authjs.dev/getting started/migrating to v5
Google Provider: https://authjs.dev/getting started/providers/google
Credentials Provider: https://authjs.dev/getting started/providers/credentials
Core API Reference: https://authjs.dev/reference/core
Session Management: https://authjs.dev/getting started/session management
Concepts: https://authjs.dev/concepts
Installation
Note : Auth.js v5 is currently in beta. Use next auth@beta to install the latest v5 version.
What's New in Auth.js v5?
Key Changes from v4
Simplified Configuration : More streamlined setup with better TypeScript support
Universal auth() Export : Single function for authentication across all contexts
Enhanced Security : Improved CSRF protection and session handling
Edge Runtime Support : Full compatibility with Edge Runtime and middleware
Better Type Safety : Improved TypeScript definitions throughout
Environment Variables
Required Environment Variables
Generating AUTH SECRET
Important : Never commit AUTH SECRET to version control. Use .env.local for development.
Basic Setup (Next.js App Router)
1. Create auth.ts Configuration File
Create auth.ts at the project root (next to package.json ):
Note : This is a basic setup example. For production ready credentials authentication, see the "Credentials Provider" section below which includes proper password hashing with bcrypt and database integration.
2. Create API Route Handler
Create app/api/auth/[...nextauth]/route.ts :
3. Add Middleware (Optional but Recommended)
Create middleware.ts at the project root:
For more control:
Google OAuth Provider
1. Google Cloud Console Setup
1. Go to [Google Cloud Console](https://console.cloud.google.com/)
2. Create a new project or select existing
3. Enable Google+ API
4. Create OAuth 2.0 credentials:
Application type: Web application
Authorized redirect URIs:
Development: http://localhost:3000/api/auth/callback/google
Production: https://yourdomain.com/api/auth/callback/google
5. Copy Client ID and Client Secret to .env.local
2. Configuration
3. Google Provider Options
Credentials Provider (Username/Password)
Required Dependencies
1. Basic Configuration
2. User Registration Example
Using Auth in Components
Server Components
Server Actions
Client Components (with SessionProvider)
Sign In/Out Actions
Programmatic Sign In
Sign In Form Component
Sign Out
Session Management
Session Strategy
Auth.js v5 supports two session strategies:
1. JWT (Default) : Stores session in encrypted JWT token
2. Database : Stores session in database
Extending the Session
Callbacks
Essential Callbacks
Database Adapter (Optional)
For persisting users, accounts, and sessions in a database, install the Prisma adapter:
Then configure it in your auth.ts :
Required Prisma schema:
API Routes
Custom API Endpoints
Protected Route Helper
Best Practices
Security
Always hash passwords : Use bcrypt, argon2, or similar
Use HTTPS in production : Required for secure cookie transmission
Validate environment variables : Check AUTH SECRET and provider credentials
Set secure cookie options :
Implement rate limiting : Protect sign in endpoints
Use CSRF protection : Enabled by default in v5
Validate redirects : Use the redirect callback to prevent open redirects
Session Management
Use appropriate maxAge : Default 30 days, adjust based on security requirements
Update sessions regularly : Use updateAge to refresh session data
Handle session expiry gracefully : Provide clear UI feedback
Secure session storage : Use database strategy for sensitive applications
Provider Configuration
Google OAuth : Request minimum required scopes
Credentials : Always validate input with zod or similar
Multiple providers : Allow account linking carefully
Provider specific logic : Use callbacks to handle provider differences
Performance
Cache session checks : Use middleware for route protection
Minimize database calls : Use JWT strategy when appropriate
Optimize database queries : Add indexes on frequently queried fields
Use Edge Runtime : For faster authentication checks in middleware
Type Safety
Extend types properly : Use module augmentation for custom session fields
Validate inputs : Use zod for runtime type checking
TypeScript strict mode : Enable for better type safety
Common Patterns
Protected Pages with Middleware
Multi Provider Setup
Custom Sign In Page
Role Based Access Control (RBAC)
Migration from v4 to v5
Key Differences
1. Import changes : next auth package remains the same, but imports are simplified
2. Universal auth() : Replace getServerSession with auth()
3. Middleware : Use auth as middleware directly
4. Configuration : More streamlined, fewer options needed
Migration Steps
Troubleshooting
Common Issues
AUTH SECRET not set :
Generate and set AUTH SECRET in .env.local
Google OAuth redirect mismatch :
Ensure redirect URI in Google Console matches: http://localhost:3000/api/auth/callback/google
Session not persisting :
Check AUTH URL is set correctly
Verify cookies are not blocked
Ensure sessionToken cookie is being set (check browser DevTools)
TypeScript errors with session :
Extend the Session and JWT types using module augmentation
Run pnpm tsc noEmit to check for type errors
Credentials provider not working :
Ensure session.strategy is set to "jwt"
Check authorize function returns correct user object with id field
Verify password hashing/comparison logic
Resources
Official Docs : https://authjs.dev
GitHub : https://github.com/nextauthjs/next auth
Discord Community : https://discord.gg/nextauth
Examples : https://github.com/nextauthjs/next auth/tree/main/apps/examples
Provider List : https://authjs.dev/getting started/providers