Next Auth V5 - Advanced Guide (2024)

Code With AntonioAbout 7 min readMay 27, 2025Watch original
THE SUMMARYAI-generated

Key Concepts

  • OJs (NextAuth v5): Authentication library for Next.js applications.
  • Credential Provider: Authentication using email and password.
  • Social Provider: Authentication using Google or GitHub.
  • Two-Factor Authentication (2FA): Security measure requiring two forms of identification.
  • User Roles: Different levels of access (e.g., admin, user).
  • Server Components: React components that run on the server.
  • Client Components: React components that run in the browser.
  • Next.js Middleware: Code that runs before a request is completed, allowing modification of the response or redirecting to another page.
  • Shadcn UI: A collection of reusable components for building user interfaces.
  • Prisma: An ORM (Object-Relational Mapper) for interacting with databases.
  • bcrypt: A library for hashing passwords.
  • next-auth: Authentication library for Next.js.
  • JWT (JSON Web Token): A standard for securely transmitting information between parties as a JSON object.
  • Callbacks: Asynchronous functions in NextAuth that allow customization of authentication events.
  • Server Actions: Functions that run on the server and can be invoked from client components.
  • Resend: An email service for sending transactional emails.
  • OAuth: An open standard for access delegation, commonly used for social login.

Project Setup and Initialization

  • System Requirements: Node.js version 18.17 or later.
  • Project Creation: Using npx create-next-app@latest out-tutorial.
    • TypeScript: Yes
    • ESLint: Yes
    • Tailwind CSS: Yes
    • Source Directory: No
    • App Router: Yes (for server components)
    • Customize Default Import Alias: No
  • Shadcn UI Installation:
    • npx shadcn-ui@latest init
    • TypeScript: Yes
    • Style: New York
    • Color: Slate
    • Global CSS: app/globals.css
    • CSS Variables for Colors: Yes
    • Tailwind Prefix: (Leave blank)
    • Tailwind Config: tailwind.config.ts
    • Import Alias: @/components
    • Lib Alias: @/lib
    • React Server Components: Yes
  • Running the App: npm run dev (starts on localhost:3000)
  • Adding Shadcn UI Components: npx shadcn-ui@latest add button (example)

Routing in Next.js App Router

  • Folder-Based Routing: Folders in the app directory represent route segments.
  • page.tsx: A file that makes a route publicly accessible.
  • layout.tsx: A file that defines shared UI for a route segment and its children.
    • Requires extracting children from props and rendering them.
  • Route Groups: Folders wrapped in parentheses (auth) are used for organization and layout sharing without affecting the URL structure.
  • Omitting Folders from Routing: Folders prefixed with an underscore _components are excluded from the routing system.
  • Client vs. Server Components:
    • Server Components (default): Run on the server, can perform asynchronous operations, and cannot use React hooks like useEffect.
    • Client Components: Marked with "use client", run in the browser, and can use React hooks.

Building the Authentication UI

  • Landing Page: Created with Tailwind CSS for styling.
    • Custom gradient background.
    • "Sign In" button using the Button component from Shadcn UI.
  • Login Button Component (login-button.tsx):
    • Accepts mode prop (either "model" or "redirect").
    • Uses useRouter from next/navigation for navigation.
  • Card Wrapper Component (card-wrapper.tsx):
    • Reusable component for wrapping authentication forms.
    • Props: headerLabel, backButtonLabel, backButtonHref, showSocial.
  • Header Component (header.tsx):
    • Reusable header component with a label.
    • Uses Poppins font from next/font/google.
  • Social Component (social.tsx):
    • Renders Google and GitHub login buttons using react-icons.
  • Back Button Component (back-button.tsx):
    • Uses the Button component with a link to navigate back.
  • Form Components:
    • Using react-hook-form, zod, and Shadcn UI form components.
    • Form, FormControl, FormField, FormItem, FormLabel, FormMessage.
  • Form Error and Success Components (form-error.tsx, form-success.tsx):
    • Reusable components for displaying error and success messages.

Server Actions and Data Validation

  • Server Actions: Functions that run on the server and can be invoked from client components.
    • Marked with "use server".
  • Data Validation: Using Zod for both client-side and server-side validation.
    • loginSchema, registerSchema.
  • useTransition Hook: Used to manage the pending state of server actions.
    • isPending, startTransition.
  • Error Handling: Returning error objects from server actions and displaying them using the FormError component.

Database Setup with Prisma

  • Prisma Installation:
    • npm install -D prisma (as a dev dependency)
    • npm install @prisma/client
  • Database Utility (db.ts):
    • Creates a Prisma client instance.
    • Handles hot reloading in development by storing the client in globalThis.
  • Neon.tech: Used as a free PostgreSQL database.
  • Prisma Initialization: npx prisma init
  • Schema Definition (schema.prisma):
    • Defines the database schema using Prisma's DSL.
    • Includes models for User and Account.
  • Prisma Commands:
    • npx prisma generate: Generates the Prisma client based on the schema.
    • npx prisma db push: Synchronizes the database schema with the defined models.
  • bcrypt for Password Hashing:
    • npm install bcrypt
    • npm install -D @types/bcrypt
    • Hashing passwords before storing them in the database.

NextAuth Configuration

  • NextAuth Installation: npm install next-auth
  • auth.ts: File for configuring NextAuth.
    • Includes providers (Credential, Google, GitHub), adapter (Prisma), and callbacks.
  • [...nextauth]/route.ts: API route for NextAuth.
    • Handles authentication requests.
  • Middleware (middleware.ts):
    • Protects routes based on authentication status.
    • Uses a regular expression to match all routes except for static files and Next.js internals.
  • auth.config.ts: Separates NextAuth configuration for edge compatibility.
  • Prisma Adapter: @next-auth/prisma-adapter
  • Callbacks:
    • signIn: Determines whether a user is allowed to sign in.
    • jwt: Extends the JWT with additional user information.
    • session: Extends the session object with data from the JWT.
  • Events:
    • linkAccount: Triggered when a user links an OAuth account.

Implementing OAuth and Email Verification

  • OAuth Providers:
    • Google and GitHub.
    • Requires setting up OAuth apps and configuring client IDs and secrets.
  • Email Verification:
    • Implemented for credential users.
    • Uses a VerificationToken model in the database.
    • Sends a verification email with a unique token.
    • Verifies the token when the user clicks the link in the email.
  • Resend: Used for sending transactional emails.
    • Requires setting up an account and verifying a domain.
  • sendVerificationEmail: Function for sending verification emails.
  • generateVerificationToken: Function for generating unique verification tokens.

Implementing Forgot Password Functionality

  • Password Reset Token:
    • Uses a PasswordResetToken model in the database.
    • Sends a reset email with a unique token.
    • Verifies the token when the user clicks the link in the email.
  • sendPasswordResetEmail: Function for sending password reset emails.
  • generatePasswordResetToken: Function for generating unique password reset tokens.
  • New Password Form: Allows users to set a new password after verifying their email.

Implementing Two-Factor Authentication

  • Database Schema Updates:
    • isTwoFactorEnabled (Boolean) field in the User model.
    • TwoFactorToken model.
    • TwoFactorConfirmation model.
  • generateTwoFactorToken: Function for generating a six-digit two-factor authentication code.
  • sendTwoFactorTokenEmail: Function for sending the two-factor authentication code via email.
  • Sign-in Callback Modification:
    • Checks if two-factor authentication is enabled for the user.
    • If enabled, prevents sign-in and requires two-factor authentication.
  • Login Action Modification:
    • Sends the two-factor authentication code via email.
    • Verifies the code entered by the user.
    • Creates a TwoFactorConfirmation record if the code is valid.

Building the Inner Application

  • Protected Routes: Routes that require authentication.
  • Server Component Example: Demonstrates how to fetch the current user in a server component.
  • Client Component Example: Demonstrates how to fetch the current user in a client component using useSession.
  • useCurrentUser Hook: A reusable hook for accessing the current user in client components.
  • Role-Based Access Control (RBAC):
    • Implemented using a RoleGate component.
    • Hides content based on the user's role.
  • Admin-Only API Route and Server Action: Demonstrates how to protect API routes and server actions based on user roles.

Settings Page Implementation

  • Settings Schema: Defines the schema for updating user settings.
  • Settings Action: Handles the logic for updating user settings in the database.
  • Form Fields:
    • Name
    • Email (conditional, only for credential users)
    • Password (conditional, only for credential users)
    • New Password (conditional, only for credential users)
    • Role
    • Two-Factor Authentication (conditional, only for credential users)
  • Conditional Rendering: Hides certain form fields based on the user's authentication provider (OAuth vs. Credential).
  • Password Hashing: Hashes the new password before updating it in the database.
  • Session Update: Updates the session object with the new user information.

Deployment

  • GitHub Repository: Creating a new repository and pushing the code.
  • Vercel Deployment:
    • Connecting the Vercel project to the GitHub repository.
    • Setting environment variables.
  • Domain Verification: Adding DNS records to verify the domain with Resend.
  • Updating OAuth App URLs: Updating the callback URLs in the Google and GitHub OAuth apps.

Synthesis/Conclusion

This comprehensive tutorial covers the creation of a robust authentication system in Next.js using NextAuth v5, Prisma, and Shadcn UI. It details the setup of credential and social providers, implementation of two-factor authentication, and management of user roles. The guide emphasizes best practices for data validation, security, and code organization, providing actionable insights for building secure and scalable Next.js applications. It also demonstrates how to deploy the application to Vercel and configure email sending with Resend.

AI summaries can miss context or contain errors. Check important details against the original video.

Go a little deeper.

Have a question about this video? Load its transcript to open the video chat.