Next.js Authentication Tutorial: A Complete Guide

Next.js Authentication Tutorial: A Complete Guide

By Elena Rodriguez, Developer Experience Editorial Desk · January 10, 2026 · Updated November 7, 2026 · 4 min read

Updated November 7, 2026: Added a section on newer Auth.js and Next.js changes (auth(), proxy.ts, Better Auth) with primary-source links, plus a Credentials provider link.

Quick Answer

NextAuth.js, now called Auth.js, is the standard way to add authentication to a Next.js app. It supports OAuth providers like Google and GitHub, email/password login through the Credentials provider, and magic links. You configure providers, add an API route and SessionProvider, then protect pages with useSession, getServerSession or middleware.

Introduction

Authentication is essential for any application with user accounts. Next.js combined with NextAuth.js provides a robust, secure, and flexible authentication solution that works with the App Router, Server Components, and API routes.

This tutorial covers implementing authentication from scratch, including OAuth providers, credentials-based login, and protecting routes.

Prerequisites

  • Next.js 14+ application
  • Basic React and Next.js knowledge
  • Node.js 18+

Installation

Install NextAuth.js (now called Auth.js) using npm or yarn. You will also need any database adapters if using database sessions. If you are upgrading an older setup, see our NextAuth to Auth.js migration guide.

Create the necessary environment variables for your secret key and OAuth provider credentials.

Basic Setup

Create Auth Configuration

Create an auth configuration file that defines your providers and callbacks. This is where you configure how authentication works in your application.

Set Up API Route

Create the NextAuth API route handler. This handles all authentication endpoints like sign in, sign out, and callbacks.

Add Session Provider

Wrap your application with the SessionProvider to make authentication state available throughout your app.

OAuth Providers

Google Sign-In

Google OAuth is one of the most popular authentication methods. Configure it by:

  1. Create a project in Google Cloud Console
  2. Enable the OAuth 2.0 API
  3. Create OAuth credentials
  4. Add authorized redirect URIs
  5. Add client ID and secret to environment variables

GitHub Sign-In

GitHub OAuth is popular for developer-focused applications:

  1. Create an OAuth App in GitHub Developer Settings
  2. Set the authorization callback URL
  3. Add client ID and secret to environment variables

Credentials Provider

For email/password authentication, use the Credentials provider. This requires:

  1. A user database
  2. Password hashing (use bcrypt)
  3. Custom authorize function

The authorize function receives credentials and should:

  • Look up the user by email
  • Verify the password hash
  • Return the user object or null

Important: Handle errors securely without revealing whether the email exists.

How Do You Protect Routes in Next.js?

Client-Side Protection

Use the useSession hook to check authentication status and redirect unauthorized users.

Server-Side Protection

For Server Components, use getServerSession to check authentication. This is more secure as it runs on the server.

Middleware Protection

Create a middleware.ts file to protect entire route groups. This runs before requests reach your pages.

Configure which routes require authentication using the matcher pattern.

Customizing Pages

Custom Sign-In Page

Create a custom sign-in page for better UX. Configure NextAuth to use your custom page instead of the default.

Your custom page should include forms for each provider and handle errors appropriately.

Custom Error Page

Handle authentication errors gracefully with a custom error page that explains what went wrong.

Session Management

Accessing Session Data

On the client, use the useSession hook. It returns session data, loading status, and update function.

On the server, use getServerSession. This is secure and can be used in Server Components and API routes.

Extending Session Data

Add custom fields to the session by extending the callbacks. For example, add user role or ID.

Database Adapters

For persistent sessions and user storage, use a database adapter.

Popular options:

  • Prisma: Works with many databases
  • Drizzle: Lightweight, TypeScript-first
  • MongoDB: For document-based storage

The adapter handles user creation, session storage, and account linking.

Updating for Newer Auth.js and Next.js Releases

Check the version of the library and the framework before copying older examples. According to the Auth.js migration guide, the newer release uses a single auth() method in place of getServerSession, getSession, withAuth, getToken and useSession, and the same guide notes that, as of Next.js 16, middleware.ts has been renamed to proxy.ts. The Auth.js site also states that the project is now part of Better Auth, so confirm its current status before starting a long-lived project.

The Next.js authentication guide separates two kinds of checks. Optimistic checks read session data from the cookie to show or hide interface elements or redirect users, while secure checks verify the user against the session store before returning data or performing an action. Use the first in the proxy or middleware layer for quick redirects, and the second wherever data is actually read or changed.

Security Best Practices

Environment Variables

Never commit secrets to version control. Use environment variables for:

  • NEXTAUTH_SECRET (generate with openssl rand -base64 32)
  • OAuth client IDs and secrets
  • Database connection strings

CSRF Protection

NextAuth includes CSRF protection by default. Do not disable it.

Secure Cookies

In production, cookies are automatically set to secure and httpOnly. Verify your deployment uses HTTPS.

Rate Limiting

Add rate limiting to authentication endpoints to prevent brute force attacks.

Testing

Development Testing

Use test accounts for OAuth providers during development. Most providers have sandbox modes.

E2E Testing

For end-to-end tests, mock the session provider or use test credentials. Playwright and Cypress both support this.

Deployment

Ensure your production environment has:

  • NEXTAUTH_URL set to your production URL
  • NEXTAUTH_SECRET as a strong random string
  • OAuth callback URLs updated for production
  • Database connection string for production database

Conclusion

NextAuth.js provides a comprehensive authentication solution for Next.js applications. Start with OAuth providers for quick implementation, add credentials if needed, and protect your routes appropriately.

Focus on security from the start—use environment variables, enable CSRF protection, and implement rate limiting. The library handles most security concerns, but understanding the underlying mechanisms helps you make better decisions.

Sources

The primary sources this article cites, checked in November 2026:

Key Takeaways

  • NextAuth.js handles OAuth, credentials, and magic links
  • Configure providers in your auth options file
  • Use useSession hook for client-side auth state
  • Protect routes with middleware or getServerSession
  • Store sessions in JWT or database depending on needs
  • Customize sign-in pages for better UX

Frequently Asked Questions

Is NextAuth.js free to use?

Yes. NextAuth.js is completely free and open source. Your only costs come from external services you choose to add, such as a database for session storage or an email provider for magic links. Signing in with OAuth providers like Google and GitHub is also free, so a basic OAuth-only setup adds no library or provider costs.

Should I use JWT or database sessions?

JWT sessions are stateless and suit simpler apps without a database. Database sessions are better when you need to revoke sessions, track active sessions or store extra user data, and they need a database adapter such as Prisma, Drizzle or MongoDB. For most applications, JWT is the simpler place to start.

How do I protect API routes in Next.js?

Call getServerSession inside the API route and return a 401 status if no session exists. To protect whole route groups at once, add a middleware.ts file that checks authentication before requests reach your pages, and use the matcher pattern to choose which routes need it. Server-side checks are more secure than client-side redirects.

What is the difference between NextAuth.js and Auth.js?

They are the same library. Auth.js is the newer name for NextAuth.js, and the core features remain the same: OAuth providers, credentials and magic links. If a tutorial or documentation page uses either name, it refers to the same project, so the configuration concepts you learn under one name carry over directly to the other.

How do you access the current user session on the client?

Use the useSession hook. It returns the session data, a loading status and an update function, so React components can render the right interface depending on whether a user is signed in. Wrap your app in SessionProvider first so that state is available everywhere. On the server, use getServerSession instead.

About the Author

Elena Rodriguez avatar

Elena Rodriguez

Developer Experience Editorial Desk

Developer Experience Editorial Desk · Web3AIBlog

Elena Rodriguez is a pen name for our developer-experience editorial desk. Posts under this byline are written and reviewed by working engineers covering full-stack development, Web3 dApp architecture, deployment workflows, build tooling, and developer productivity. The desk specializes in turning real production debugging — failed deploys, flaky tests, memory leaks, broken migrations — into reproducible field manuals. Code samples in our tutorials are built from and verified against the official SDKs and documentation, with library versions pinned, before publication.