Authentication
Secure authentication with NextAuth.js v5 in the went framework.
Authentication Overview
✅ Pre-configured Features
- • User registration and login
- • Google OAuth integration (optional)
- • Password reset with email
- • Welcome emails for new users
- • Protected routes and middleware
- • Session management
Basic Setup
Configure these required environment variables in your .env file:
# Required for NextAuth.js AUTH_SECRET="your-32-character-secret-key" NEXTAUTH_URL="http://localhost:3000" # Optional: Email service for password reset RESEND_API_KEY="re_your_resend_api_key" FROM_EMAIL="noreply@yourdomain.com"
Generate AUTH_SECRET: Run openssl rand -base64 32 to generate a secure secret key.
Google OAuth Setup (Optional)
Step 1: Create OAuth Credentials
- 1. Go to Google Cloud Console
- 2. Create a new project or select existing one
- 3. Enable the Google+ API
- 4. Go to "Credentials" → "Create Credentials" → "OAuth 2.0 Client IDs"
- 5. Set application type to "Web application"
Step 2: Configure Redirect URIs
Development: http://localhost:3000/api/auth/callback/google Production: https://yourdomain.com/api/auth/callback/google
Step 3: Add Environment Variables
GOOGLE_CLIENT_ID="your-google-client-id" GOOGLE_CLIENT_SECRET="your-google-client-secret"
Automatic Integration: When both Google OAuth variables are configured, Google sign-in buttons will automatically appear on your login and signup forms.
Protected Routes
Protect server components by checking authentication status:
// app/dashboard/page.tsx
import { auth } from '@/lib/auth'
import { redirect } from 'next/navigation'
export default async function DashboardPage() {
const session = await auth()
if (!session?.user) {
redirect('/auth/signin')
}
return (
<div>
<h1>Welcome, {session.user.email}!</h1>
{/* Protected content */}
</div>
)
}Use the useSession hook for client-side authentication:
'use client'
import { useSession } from 'next-auth/react'
export function UserProfile() {
const { data: session, status } = useSession()
if (status === 'loading') return <div>Loading...</div>
if (status === 'unauthenticated') return <div>Please sign in</div>
return (
<div>
<p>Signed in as {session?.user?.email}</p>
<button onClick={() => signOut()}>Sign out</button>
</div>
)
}API Route Protection
Secure your API routes by checking authentication:
// app/api/protected/route.ts
import { auth } from '@/lib/auth'
import { NextResponse } from 'next/server'
export async function GET() {
const session = await auth()
if (!session?.user) {
return NextResponse.json(
{ error: 'Unauthorized' },
{ status: 401 }
)
}
// Protected API logic here
return NextResponse.json({
message: 'Protected data',
user: session.user
})
}User Management
Users are automatically created in your database when they sign up:
// User model in Prisma schema
model User {
id String @id @default(cuid())
email String @unique
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
orders Order[]
}When RESEND_API_KEY is configured, new users automatically receive welcome emails.
Email Features: Welcome emails, password reset emails, and email verification are automatically handled when Resend is configured.
Security Best Practices
Environment Security
- • Never commit AUTH_SECRET to version control
- • Use different secrets for different environments
- • Rotate secrets regularly in production
- • Use strong, randomly generated secrets
Session Management
- • Sessions are automatically managed by NextAuth.js
- • Configure session expiry based on your needs
- • Always validate sessions on protected routes
- • Use HTTPS in production for secure cookies
Production Deployment
- • Update NEXTAUTH_URL to your production domain
- • Configure OAuth redirect URIs for production
- • Use environment variables in your hosting platform
- • Test authentication flows before going live
Next Steps
Continue your journey with Went: