How to Use NextAuth for Authentication in Next.js: A Step-by-Step Guide

NextAuth.js is a complete authentication solution for Next.js applications. It supports multiple providers (OAuth, email, credentials), handles sessions, and integrates seamlessly with the App Router and Pages Router. This tutorial walks you through the essential steps to set up authentication quickly.

Before you begin, ensure you have a Next.js project (v13 or later) and a provider like Google or GitHub. NextAuth manages the heavy lifting—token storage, session management, and route protection—so you can focus on your app’s logic.

Article illustration

1. Install and Configure NextAuth

Run the following command to install NextAuth:

  • npm install next-auth

Create a file at app/api/auth/[...nextauth]/route.js (App Router) or pages/api/auth/[...nextauth].js (Pages Router). Inside, export a handler:

  • Import NextAuth from ‘next-auth’ and configure it with your provider(s) and a secret.
  • Set a secure NEXTAUTH_SECRET environment variable (e.g., using openssl rand -base64 32).
  • Define providers, e.g., GoogleProvider({ clientId: ..., clientSecret: ... }).

2. Configure a Provider (Google Example)

Add the provider to your NextAuth options and set up credentials in the provider’s dashboard (e.g., Google Cloud Console). Update your .env.local file:

  • GOOGLE_CLIENT_ID=your_id
  • GOOGLE_CLIENT_SECRET=your_secret
  • NEXTAUTH_URL=http://localhost:3000 (for development)

Then restart your dev server and test by visiting /api/auth/signin. The built-in UI appears automatically.

3. Protect Pages with Middleware

Use NextAuth middleware to protect routes. Create a middleware.js file in your project root:

  • Export export { default } from "next-auth/middleware"
  • Add a matcher config to specify protected paths (e.g., /dashboard/:path*).

Unauthenticated users will be redirected to the sign-in page. This works with both App and Pages Router.

4. Access Session Data in Components

Wrap your app with a SessionProvider in a Client Component (if using App Router, add a provider in a layout). Then use useSession() hook to get user data:

  • Import useSession from ‘next-auth/react’ and destructure { data: session, status }.
  • Display user info, e.g., session.user.name, or check status === "authenticated" to show content.

You can also access sessions on the server with getServerSession() in API routes or Server Components.

Conclusion

NextAuth drastically reduces the complexity of adding authentication to Next.js. With installations in minutes, support for multiple providers, and built-in session handling, you can focus on building features instead of auth logic. Start with one provider and scale as needed.

sarah antaboga
Author: sarah antaboga

Leave a Reply

Your email address will not be published. Required fields are marked *