Skip to content

Authentication implementation in Next.js 14+ applications using Auth.js (formerly NextAuth).

Notifications You must be signed in to change notification settings

davidkopelent/nextauth

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

15 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

NextAuth.js Demo Repository

A comprehensive demonstration of authentication implementation in Next.js 14+ applications using Auth.js (formerly NextAuth).

Overview

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.

Features

  • πŸ” 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

Tech Stack

  • Next.js 14+ (App Router)
  • Auth.js (NextAuth v5+)
  • TypeScript
  • Prisma ORM
  • bcrypt for password hashing
  • Zod for validation

Getting Started

Prerequisites

  • Node.js 18.17.0 or later
  • npm, yarn, or pnpm

Installation

# 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

Environment Variables

# 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

Project Structure

/
β”œβ”€β”€ 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

Authentication Flow

Credentials Provider (Email/Password)

  1. User enters email and password in the login form
  2. Form data is sent to the server using a server action
  3. Credentials are validated against database records
  4. If valid, a JWT session is created and the user is redirected

OAuth (Google)

  1. User clicks "Continue with Google" button
  2. User is redirected to Google for authentication
  3. Upon successful authentication, user is redirected back
  4. Auth.js verifies the OAuth response and creates a session
  5. If it's a new user, an account is created in the database

Usage Examples

Protecting Pages

// 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>;
}

Client-Side Authentication

'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-Side Authentication Check

// 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>
  );
}

Configuration Options

Session Strategy

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
  },
  // ...
};

Redirect Options

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
}

Learn More

License

This project is open source and available under the MIT License.

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

About

Authentication implementation in Next.js 14+ applications using Auth.js (formerly NextAuth).

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published