A comprehensive demonstration of authentication implementation in Next.js 14+ applications using Auth.js (formerly NextAuth).
This repository serves as a practical guide and reference implementation for integrating Auth.js into your Next.js projects. It demonstrates best practices for handling user authentication with multiple providers, session management, protected routes, and more.
- π Multiple authentication providers:
- Credentials (email/password)
- Google OAuth
- πͺ Protected routes with middleware
- π Session management with JWT strategy
- π§© Type-safe authentication with TypeScript
- π₯οΈ Server-side authentication checks
- π Server actions for auth operations
- π Database integration with Prisma
- Next.js 14+ (App Router)
- Auth.js (NextAuth v5+)
- TypeScript
- Prisma ORM
- bcrypt for password hashing
- Zod for validation
- Node.js 18.17.0 or later
- npm, yarn, or pnpm
# Clone the repository
git clone https://github.com/yourusername/nextauth-demo.git
cd nextauth-demo
# Install dependencies
npm install
# or
yarn install
# or
pnpm install
# Set up environment variables
cp .env.example .env.local# NextAuth
NEXTAUTH_URL=http://localhost:3000
NEXTAUTH_SECRET=your-secret-key
# OAuth Providers
AUTH_GOOGLE_ID=your-google-client-id
AUTH_GOOGLE_SECRET=your-google-client-secret
# Database
DATABASE_URL=your-database-connection-string
/
βββ auth.config.ts # Auth.js configuration
βββ auth.ts # Main Auth.js setup
βββ next.config.ts # Next.js configuration
βββ src/
β βββ app/
β β βββ (auth)/ # Authentication routes
β β β βββ login/ # Login page
β β β βββ signup/ # Signup page
β β βββ api/ # API routes
β β β βββ auth/ # Auth API endpoints
β βββ components/ # UI components
β β βββ LoginForm.tsx # Login form component
β β βββ Input.tsx # Reusable input component
β βββ lib/
β β βββ auth/ # Auth helpers
β β β βββ auth.ts # Server actions for auth
β β βββ prisma.ts # Prisma client
β β βββ zod.ts # Schema validation
β βββ utils/ # Utility functions
β βββ db.ts # Database helpers
β βββ password.ts # Password utilities
- User enters email and password in the login form
- Form data is sent to the server using a server action
- Credentials are validated against database records
- If valid, a JWT session is created and the user is redirected
- User clicks "Continue with Google" button
- User is redirected to Google for authentication
- Upon successful authentication, user is redirected back
- Auth.js verifies the OAuth response and creates a session
- If it's a new user, an account is created in the database
// src/app/protected-page/page.tsx
import { auth } from '@/auth';
import { redirect } from 'next/navigation';
export default async function ProtectedPage() {
const session = await auth();
if (!session) {
redirect('/login');
}
return <div>Protected content</div>;
}'use client'
import { useSession } from "next-auth/react";
export default function ProfileButton() {
const { data: session } = useSession();
if (!session) {
return <button>Sign In</button>;
}
return <div>Hello, {session.user.name}</div>;
}// Server Component
import { auth } from '@/auth';
export default async function UserProfile() {
const session = await auth();
return (
<div>
{session ? (
<p>Welcome, {session.user.name}</p>
) : (
<p>Please login to view your profile</p>
)}
</div>
);
}The project uses JWT for session management with a 24-hour expiration time:
// auth.config.ts
export const authConfig = {
session: {
strategy: 'jwt',
maxAge: 24 * 60 * 60, // 24 hours
},
// ...
};Customize the redirect behavior in the authorized callback:
authorized({ auth, request: { nextUrl } }) {
const isLoggedIn = !!auth?.user;
const isOnApp = nextUrl.pathname.startsWith('/');
const isOnLogin = nextUrl.pathname.startsWith('/login');
// Custom redirect logic
}This project is open source and available under the MIT License.
Contributions are welcome! Please feel free to submit a Pull Request.