NextAuth
Auth
Security
NextAuth v5 : Authentification complète guide
Implémentez une authentification production-ready avec NextAuth v5, credentials provider, JWT et Prisma Adapter.
Emmanuel Mulonda10 juillet 202615 min de lecture
Introduction
NextAuth v5 (Auth.js) apporte une refonte majeure avec un support natif des Server Components, une meilleure integration avec Prisma et une configuration simplifiée.
Installation
npm install next-auth@beta @auth/prisma-adapter @prisma/client bcryptjs
Configuration
auth.ts
import NextAuth from "next-auth";
import Credentials from "next-auth/providers/credentials";
import { PrismaAdapter } from "@auth/prisma-adapter";
import { prisma } from "@/lib/prisma";
import bcrypt from "bcryptjs";
export const { handlers, auth, signIn, signOut } = NextAuth({
adapter: PrismaAdapter(prisma),
session: { strategy: "jwt" },
pages: {
signIn: "/login",
},
providers: [
Credentials({
credentials: {
email: { label: "Email", type: "email" },
password: { label: "Password", type: "password" },
},
async authorize(credentials) {
const user = await prisma.user.findUnique({
where: { email: credentials.email as string },
});
if (!user || !user.password) return null;
const valid = await bcrypt.compare(
credentials.password as string,
user.password,
);
if (!valid) return null;
return { id: user.id, email: user.email, name: user.name, role: user.role };
},
}),
],
callbacks: {
async jwt({ token, user }) {
if (user) {
token.role = user.role;
}
return token;
},
async session({ session, token }) {
if (token) {
session.user.id = token.sub!;
session.user.role = token.role as string;
}
return session;
},
},
});
API Route
// app/api/auth/[...nextauth]/route.ts
import { handlers } from "@/auth";
export const { GET, POST } = handlers;
Protection des Routes
Middleware
// proxy.ts (Next.js 16)
export { auth as proxy } from "@/auth";
export const config = {
matcher: ["/dashboard/:path*", "/admin/:path*"],
};
Server-Side Check
import { auth } from "@/auth";
import { redirect } from "next/navigation";
export default async function DashboardPage() {
const session = await auth();
if (!session) redirect("/login");
return <div>Bonjour {session.user.name}</div>;
}
Inscription
// app/api/auth/register/route.ts
import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import bcrypt from "bcryptjs";
export async function POST(request: Request) {
const { name, email, password } = await request.json();
const existing = await prisma.user.findUnique({ where: { email } });
if (existing) {
return NextResponse.json({ error: "Email déjà utilisé" }, { status: 400 });
}
const hashed = await bcrypt.hash(password, 12);
const user = await prisma.user.create({
data: { name, email, password: hashed },
});
return NextResponse.json({ userId: user.id }, { status: 201 });
}
NextAuth
Auth
Security