Authentication for Next.js
NextAuth.js is a complete authentication solution built specifically for Next.js applications, handling OAuth flows, session management, and security measures through a single API route. With over 2.5 million weekly downloads, it has become the de facto standard for authentication in the Next.js ecosystem, eliminating weeks of development time that would otherwise be spent building custom auth systems.
The library supports multiple authentication strategies including OAuth 1.0/2.0/OIDC with 50+ built-in provider integrations, email magic links, and traditional credentials-based authentication. It works seamlessly with both database-backed sessions and stateless JWT tokens, giving developers flexibility to choose the architecture that fits their infrastructure—whether that's serverless functions, edge runtime, or traditional Node.js servers.
NextAuth.js follows security best practices by default, including CSRF protection, secure HTTP-only cookies, encrypted JWTs using A256GCM, and passwordless authentication as the recommended approach. The library integrates deeply with Next.js features like middleware for edge-based route protection, API routes for authentication endpoints, and React Server Components for session handling.
Developers choose NextAuth.js when they need production-ready authentication without managing OAuth specifications, token refresh logic, or security vulnerabilities that commonly plague custom implementations. It's particularly valuable for startups and teams that need to ship authentication quickly while maintaining enterprise-grade security standards.
// pages/api/auth/[...nextauth].js
import NextAuth from 'next-auth';
import GithubProvider from 'next-auth/providers/github';
import EmailProvider from 'next-auth/providers/email';
import { PrismaAdapter } from '@auth/prisma-adapter';
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
export const authOptions = {
adapter: PrismaAdapter(prisma),
providers: [
GithubProvider({
clientId: process.env.GITHUB_ID,
clientSecret: process.env.GITHUB_SECRET,
}),
EmailProvider({
server: process.env.EMAIL_SERVER,
from: 'noreply@example.com',
}),
],
callbacks: {
async session({ session, user }) {
session.user.id = user.id;
session.user.role = user.role;
return session;
},
async signIn({ user, account, profile }) {
const isAllowed = user.email.endsWith('@company.com');
return isAllowed;
},
},
session: {
strategy: 'database',
maxAge: 30 * 24 * 60 * 60,
},
pages: {
signIn: '/auth/signin',
error: '/auth/error',
},
};
export default NextAuth(authOptions);
// pages/_app.js
import { SessionProvider } from 'next-auth/react';
export default function App({ Component, pageProps: { session, ...pageProps } }) {
return (
<SessionProvider session={session}>
<Component {...pageProps} />
</SessionProvider>
);
}
// components/LoginButton.jsx
import { useSession, signIn, signOut } from 'next-auth/react';
export default function LoginButton() {
const { data: session, status } = useSession();
if (status === 'loading') return <div>Loading...</div>;
if (session) {
return (
<div>
<p>Signed in as {session.user.email}</p>
<button onClick={() => signOut()}>Sign out</button>
</div>
);
}
return (
<div>
<button onClick={() => signIn('github')}>Sign in with GitHub</button>
<button onClick={() => signIn('email')}>Sign in with Email</button>
</div>
);
}
// middleware.js - Protect routes
import { withAuth } from 'next-auth/middleware';
export default withAuth({
callbacks: {
authorized: ({ token, req }) => {
if (req.nextUrl.pathname.startsWith('/admin')) {
return token?.role === 'admin';
}
return !!token;
},
},
});
export const config = {
matcher: ['/dashboard/:path*', '/admin/:path*', '/api/protected/:path*'],
};SaaS Applications with Social Login: Implement Google, GitHub, and Microsoft sign-in for a project management tool, allowing users to authenticate with existing accounts while NextAuth.js handles OAuth token exchange, session creation, and automatic token refresh.
E-commerce Platforms with Email Magic Links: Enable passwordless authentication for customers by sending one-time login links via email, reducing friction in the checkout process while NextAuth.js manages link expiration, verification, and session establishment.
Enterprise Internal Tools with LDAP/Active Directory: Connect corporate authentication systems using custom credential providers, allowing employees to use their existing company credentials while NextAuth.js manages session persistence across multiple internal applications.
Multi-tenant B2B Applications: Implement organization-specific authentication flows where different tenants can configure their own OAuth providers (Okta, Auth0, Azure AD), with NextAuth.js handling the dynamic provider configuration and routing logic.
API-First Applications with JWT Sessions: Build stateless authentication for mobile and web clients using encrypted JWT tokens, where NextAuth.js generates secure tokens and provides middleware to verify them on protected API routes without requiring a database.
npm install next-authpnpm add next-authbun add next-auth