Implement secure authentication with NextAuth.js v5 (Auth.js). Learn OAuth providers, credentials auth, JWT sessions, middleware protection, and role-based access control for Next.js 15.
# NextAuth.js v5 Authentication Complete Guide
Build secure authentication with NextAuth.js v5 (Auth.js) for Next.js 15 applications with OAuth, credentials, and advanced session management.
## Basic Setup
### Configuration
```typescript
// auth.ts
import NextAuth from "next-auth";
import { PrismaAdapter } from "@auth/prisma-adapter";
import { prisma } from "@/lib/prisma";
import Google from "next-auth/providers/google";
import GitHub from "next-auth/providers/github";
import Credentials from "next-auth/providers/credentials";
import bcrypt from "bcryptjs";
import { z } from "zod";
const loginSchema = z.object({
email: z.string().email(),
password: z.string().min(8),
});
export const { handlers, auth, signIn, signOut } = NextAuth({
adapter: PrismaAdapter(prisma),
session: { strategy: "jwt" },
pages: {
signIn: "/login",
error: "/auth/error",
verifyRequest: "/auth/verify",
},
providers: [
Google({
clientId: process.env.GOOGLE_CLIENT_ID!,
clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
authorization: {
params: {
prompt: "consent",
access_type: "offline",
response_type: "code",
},
},
}),
GitHub({
clientId: process.env.GITHUB_CLIENT_ID!,
clientSecret: process.env.GITHUB_CLIENT_SECRET!,
}),
Credentials({
name: "credentials",
credentials: {
email: { label: "Email", type: "email" },
password: { label: "Password", type: "password" },
},
async authorize(credentials) {
const validated = loginSchema.safeParse(credentials);
if (!validated.success) return null;
const { email, password } = validated.data;
const user = await prisma.user.findUnique({
where: { email },
select: {
id: true,
email: true,
name: true,
password: true,
role: true,
emailVerified: true,
},
});
if (!user || !user.password) return null;
if (!user.emailVerified) return null;
const isValid = await bcrypt.compare(password, user.password);
if (!isValid) return null;
return {
id: user.id,
email: user.email,
name: user.name,
role: user.role,
};
},
}),
],
callbacks: {
async jwt({ token, user, account, trigger, session }) {
if (user) {
token.id = user.id;
token.role = user.role;
}
// Handle session update
if (trigger === "update" && session) {
token.name = session.name;
}
// Refresh token for OAuth
if (account?.provider === "google") {
token.accessToken = account.access_token;
token.refreshToken = account.refresh_token;
token.expiresAt = account.expires_at;
}
return token;
},
async session({ session, token }) {
if (token) {
session.user.id = token.id as string;
session.user.role = token.role as string;
}
return session;
},
async signIn({ user, account, profile }) {
// Block unverified email signups
if (account?.provider === "credentials") {
return true;
}
// Auto-link accounts with same email
if (account && user.email) {
const existingUser = await prisma.user.findUnique({
where: { email: user.email },
});
if (existingUser) {
await prisma.account.upsert({
where: {
provider_providerAccountId: {
provider: account.provider,
providerAccountId: account.providerAccountId,
},
},
update: {},
create: {
userId: existingUser.id,
...account,
},
});
}
}
return true;
},
},
events: {
async signIn({ user, account }) {
await prisma.user.update({
where: { id: user.id },
data: { lastLogin: new Date() },
});
},
},
});
```
### Route Handlers
```typescript
// app/api/auth/[...nextauth]/route.ts
import { handlers } from "@/auth";
export const { GET, POST } = handlers;
```
## Middleware Protection
```typescript
// middleware.ts
import { auth } from "@/auth";
import { NextResponse } from "next/server";
const publicRoutes = ["/", "/login", "/register", "/api/auth"];
const adminRoutes = ["/admin", "/api/admin"];
export default auth((req) => {
const { nextUrl, auth: session } = req;
const isLoggedIn = !!session?.user;
const isPublicRoute = publicRoutes.some((route) =>
nextUrl.pathname.startsWith(route)
);
const isAdminRoute = adminRoutes.some((route) =>
nextUrl.pathname.startsWith(route)
);
// Redirect logged-in users from auth pages
if (isLoggedIn && nextUrl.pathname.startsWith("/login")) {
return NextResponse.redirect(new URL("/dashboard", nextUrl));
}
// Protect private routes
if (!isLoggedIn && !isPublicRoute) {
const callbackUrl = encodeURIComponent(nextUrl.pathname);
return NextResponse.redirect(
new URL(`/login?callbackUrl=${callbackUrl}`, nextUrl)
);
}
// Role-based access
if (isAdminRoute && session?.user?.role !== "admin") {
return NextResponse.redirect(new URL("/unauthorized", nextUrl));
}
return NextResponse.next();
});
export const config = {
matcher: ["/((?!_next/static|_next/image|favicon.ico).*)"],
};
```
## Server Components
```typescript
// app/dashboard/page.tsx
import { auth } from "@/auth";
import { redirect } from "next/navigation";
export default async function DashboardPage() {
const session = await auth();
if (!session?.user) {
redirect("/login");
}
return (
<div>
<h1>Welcome, {session.user.name}</h1>
<p>Role: {session.user.role}</p>
</div>
);
}
```
## Client Components
```typescript
// components/AuthButtons.tsx
"use client";
import { signIn, signOut, useSession } from "next-auth/react";
export function AuthButtons() {
const { data: session, status } = useSession();
if (status === "loading") {
return <div>Loading...</div>;
}
if (session) {
return (
<div className="flex items-center gap-4">
<span>{session.user?.name}</span>
<button
onClick={() => signOut({ callbackUrl: "/" })}
className="btn-secondary"
>
Sign Out
</button>
</div>
);
}
return (
<div className="flex gap-2">
<button
onClick={() => signIn("google")}
className="btn-primary"
>
Sign in with Google
</button>
<button
onClick={() => signIn("github")}
className="btn-secondary"
>
Sign in with GitHub
</button>
</div>
);
}
```
## Type Extensions
```typescript
// types/next-auth.d.ts
import { DefaultSession } from "next-auth";
declare module "next-auth" {
interface Session {
user: {
id: string;
role: string;
} & DefaultSession["user"];
}
interface User {
role: string;
}
}
declare module "next-auth/jwt" {
interface JWT {
id: string;
role: string;
}
}
```
## Session Provider
```typescript
// app/providers.tsx
"use client";
import { SessionProvider } from "next-auth/react";
export function Providers({ children }: { children: React.ReactNode }) {
return <SessionProvider>{children}</SessionProvider>;
}
```
This NextAuth.js v5 guide provides complete authentication with OAuth, credentials, middleware protection, and role-based access control.This nextauth prompt is ideal for developers working on:
By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their nextauth implementations.
Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.
This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.
You can modify the prompt by adding specific requirements, constraints, or preferences. For nextauth projects, consider mentioning your framework version, coding style, and any specific libraries you're using.