NextAuth.js

4.24.14 · maintenance · verified Sat Apr 18

NextAuth.js (version 4.24.14) provides comprehensive authentication solutions for Next.js applications, supporting a wide range of authentication providers including OAuth, email, and credentials. This package is currently in maintenance mode, with active feature development now taking place in Auth.js (v5) under the `@auth/nextjs` package. It receives critical bug fixes and security updates for its v4 branch.

Common errors

Warnings

Install

Imports

Quickstart

This code sets up a basic NextAuth.js API route (`pages/api/auth/[...nextauth].ts`) using GitHub as an OAuth provider. It demonstrates provider configuration, the mandatory `secret` environment variable, and a simple session callback.

import NextAuth, { type AuthOptions } from 'next-auth';
import GitHubProvider from 'next-auth/providers/github';

// For production, ensure these are robustly set via environment variables.
// Example using a database adapter (uncomment and install if needed):
// import { MongoDBAdapter } from '@next-auth/mongodb-adapter';
// import clientPromise from '../../../lib/mongodb'; // Your MongoDB connection logic

export const authOptions: AuthOptions = {
  // Configure one or more authentication providers
  providers: [
    GitHubProvider({
      clientId: process.env.GITHUB_ID ?? '',
      clientSecret: process.env.GITHUB_SECRET ?? ''
    })
    // ...add more providers here
  ],
  // Optional: Add a database adapter if you want to persist user sessions
  // adapter: MongoDBAdapter(clientPromise),
  
  // REQUIRED: A secret to sign and encrypt session tokens. 
  // Use `openssl rand -base64 32` to generate a strong one.
  secret: process.env.NEXTAUTH_SECRET ?? '',

  // Callbacks are essential for custom session data, redirects, etc.
  // https://next-auth.js.org/configuration/callbacks
  callbacks: {
    async session({ session, token, user }) {
      // Example: add user ID to session (useful for database-backed sessions)
      if (token?.sub) {
        session.user.id = token.sub; 
      }
      return session;
    }
  },
  // Enable debug messages in the console during development
  debug: process.env.NODE_ENV === 'development'
};

export default NextAuth(authOptions);

view raw JSON →