NextAuth.js
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
-
[next-auth][error][NO_SECRET]
cause The `NEXTAUTH_SECRET` environment variable is not set or is empty.fixSet a strong `NEXTAUTH_SECRET` environment variable (e.g., `NEXTAUTH_SECRET=your_super_secret_string`). This is critical for security. -
[next-auth][error][CSRF_TOKEN_INVALID]
cause The CSRF token submitted with the request does not match the expected token, often due to expired sessions, incorrect form submission, or network issues.fixEnsure that the page initiating the authentication flow is properly rendered with the CSRF token. If a custom sign-in page is used, ensure it correctly renders the CSRF token from `getCsrfToken()`. Clear browser cookies and try again. -
[next-auth][error][SIGNIN_OAUTH_ERROR]
cause An error occurred during the OAuth sign-in process, often related to incorrect provider configuration (e.g., wrong `clientId`, `clientSecret`, or `callbackUrl`).fixDouble-check your provider configuration in `[...nextauth].ts` (e.g., `GitHubProvider({ clientId: process.env.GITHUB_ID, ... })`) against the values registered with your OAuth provider (GitHub, Google, etc.). Ensure your callback URL (`AUTH_URL/api/auth/callback/github`) is correctly configured in the OAuth provider settings. -
Could not find a NextAuth.js provider with id "google" (or similar provider ID)
cause The specified provider ID (e.g., 'google') is not found in the `providers` array in your `authOptions` configuration.fixVerify that the provider you are trying to use (e.g., `GoogleProvider`) is correctly imported and included in the `providers` array within `authOptions` in your `[...nextauth].ts` file.
Warnings
- breaking NextAuth.js v4 (next-auth) is in maintenance. The project has evolved into Auth.js (v5) under `@auth/nextjs` with significant architectural changes, especially for Next.js App Router support.
- gotcha Older versions of the GitHub provider (pre-4.24.14) may fail due to GitHub's RFC 9207 compliance, which introduced an `iss` (issuer) parameter that `openid-client` validates unconditionally.
- gotcha A strong `NEXTAUTH_SECRET` environment variable is crucial for security. Without it, session tokens are not properly signed, making your application vulnerable.
- gotcha Using `next-auth` v4 with Next.js App Router requires careful implementation (e.g., `'use client'` directives for client components like `SessionProvider`, `signIn`, `signOut`). It is primarily designed for the Pages Router.
Install
-
npm install next-auth -
yarn add next-auth -
pnpm add next-auth
Imports
- AuthOptions
const { AuthOptions } = require('next-auth')import { AuthOptions } from 'next-auth'
Quickstart
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);