Authentication
Auth.js (formerly NextAuth.js) is the standard authentication library for Next.js. It supports OAuth providers, credentials, and session management.
Installation
npm install next-auth@beta
Auth.js v5 is designed for the App Router. Check the Auth.js docs for the latest stable version.
Basic Setup
// auth.ts
import NextAuth from 'next-auth';
import GitHub from 'next-auth/providers/github';
export const { handlers, auth, signIn, signOut } = NextAuth({
providers: [
GitHub({
clientId: process.env.GITHUB_ID,
clientSecret: process.env.GITHUB_SECRET,
}),
],
});
Expose the auth API route:
// app/api/auth/[...nextauth]/route.ts
import { handlers } from '@/auth';
export const { GET, POST } = handlers;
Add to .env.local:
AUTH_SECRET=your-random-secret-at-least-32-chars
GITHUB_ID=your-github-client-id
GITHUB_SECRET=your-github-client-secret
Generate a secret: npx auth secret
Sign In and Sign Out
'use client';
import { signIn, signOut, useSession } from 'next-auth/react';
export default function AuthButton() {
const { data: session, status } = useSession();
if (status === 'loading') return <p>Loading...</p>;
if (session) {
return (
<div>
<p>Signed in as {session.user?.email}</p>
<button onClick={() => signOut()}>Sign out</button>
</div>
);
}
return <button onClick={() => signIn('github')}>Sign in with GitHub</button>;
}
Wrap your app with SessionProvider in a Client Component and include it in the root layout.
Server-Side Session Access
Read the session in Server Components:
// app/dashboard/page.tsx
import { auth } from '@/auth';
import { redirect } from 'next/navigation';
export default async function DashboardPage() {
const session = await auth();
if (!session) redirect('/login');
return <h1>Welcome, {session.user?.name}</h1>;
}
Protecting Routes with Middleware
// middleware.ts
export { auth as middleware } from '@/auth';
export const config = {
matcher: ['/dashboard/:path*', '/settings/:path*'],
};
Configure authorized callbacks in auth.ts:
export const { handlers, auth, signIn, signOut } = NextAuth({
providers: [GitHub],
callbacks: {
authorized({ auth, request }) {
const isLoggedIn = !!auth?.user;
const isProtected = request.nextUrl.pathname.startsWith('/dashboard');
if (isProtected) return isLoggedIn;
return true;
},
},
});
Credentials and Session Strategies
Auth.js supports 80+ OAuth providers (GitHub, Google, Discord) and a Credentials provider for custom email/password login against your own database.
| Strategy | Storage | Best for |
|---|---|---|
| JWT (default) | Encrypted cookie | Serverless, no database |
| Database | Session table in DB | Revocable sessions, audit logs |
For production apps with sensitive data, prefer database sessions so you can invalidate sessions server-side.
Next: deploy your Next.js app to Vercel.