Topic 45 of 47
NextAuth.js Integration
Overview
NextAuth.js (now Auth.js) is the most popular authentication library for Next.js. It provides built-in support for OAuth providers (Google, GitHub), Credentials (email/password), and Magic Links, securely handling sessions and cookies automatically.
Syntax
typescript
// 1. Installation
// npm install next-auth
// 2. Setup: app/api/auth/[...nextauth]/route.ts
import NextAuth from "next-auth";
import GithubProvider from "next-auth/providers/github";
const handler = NextAuth({
providers: [
GithubProvider({
clientId: process.env.GITHUB_ID,
clientSecret: process.env.GITHUB_SECRET,
}),
],
// Optional: Add a database adapter to persist users
// adapter: PrismaAdapter(prisma),
});
export { handler as GET, handler as POST };Common Pitfalls
- You must configure a strong `NEXTAUTH_SECRET` environment variable in production, otherwise NextAuth will throw an error.
- When using the Credentials provider (email/password), NextAuth forces JSON Web Tokens (JWT) for the session strategy. You cannot use database sessions with Credentials for security reasons.
Real-World Example
Accessing the user's session on the server:
example
typescript
// app/dashboard/page.tsx
import { redirect } from "next/navigation";
export default async function Dashboard() {
// Securely get session data on the server without an API call
const session = await auth();
if (!session) {
redirect('/api/auth/signin'); // Force login
}
return <h1>Welcome, {session.user?.name}</h1>;
}