Authentication in Next.js Using Auth.js
š **Overview**: Auth.js (formerly NextAuth.js) provides a simple, secure, and customizable authentication system for Next.js applications. Whether you want credentials login, OAuth providers like Google/GitHub, or full JWT-based sessionsāAuth.js makes it incredibly easy with a plug-and-play architecture.
š **Why Auth.js?**
- Secure and battle-tested authentication - Supports Credentials, OAuth, Magic Links, and SSO - Works with both JWT and Database sessions - Perfectly integrates with Next.js Route Handlers & Middleware - Zero API boilerplateāAuth.js auto-generates them
1ļøā£ **Install Dependencies**
1npm install next-auth bcrypt2ļøā£ **Create Auth.js Route Handler** (`src/app/api/auth/[...nextauth]/route.ts`)
1import NextAuth from "next-auth";
2import CredentialsProvider from "next-auth/providers/credentials";
3import bcrypt from "bcrypt";
4import { db } from "@/lib/db"; // example DB
5
6export const { handlers, auth } = NextAuth({
7 providers: [
8 CredentialsProvider({
9 name: "Credentials",
10 credentials: {
11 email: {},
12 password: {},
13 },
14 authorize: async (credentials) => {
15 if (!credentials?.email || !credentials?.password) return null;
16
17 const user = await db.user.findUnique({
18 where: { email: credentials.email },
19 });
20
21 if (!user) return null;
22
23 const isMatch = await bcrypt.compare(
24 credentials.password,
25 user.password
26 );
27 if (!isMatch) return null;
28
29 return {
30 id: user.id,
31 name: user.name,
32 email: user.email,
33 };
34 },
35 }),
36 ],
37
38 session: { strategy: "jwt" },
39
40 callbacks: {
41 async jwt({ token, user }) {
42 if (user) token.user = user;
43 return token;
44 },
45 async session({ session, token }) {
46 session.user = token.user;
47 return session;
48 },
49 },
50});3ļøā£ **Using the `auth()` Helper to Protect Server Components**
1import { auth } from "@/app/api/auth/[...nextauth]/route";
2import { redirect } from "next/navigation";
3
4export default async function Dashboard() {
5 const session = await auth();
6
7 if (!session) redirect("/login");
8
9 return <h1>Welcome, {session.user.name}</h1>;
10}4ļøā£ **Protecting API Routes with Middleware** (`middleware.ts`)
1import { auth } from "next-auth";
2
3export default auth((req) => {
4 // Block unauthenticated users
5 if (!req.auth) {
6 return Response.redirect(new URL("/login", req.url));
7 }
8});
9
10export const config = {
11 matcher: ["/dashboard/:path*", "/api/protected/:path*"],
12};5ļøā£ **OAuth Example (Google Provider)**
1import GoogleProvider from "next-auth/providers/google";
2
3providers: [
4 GoogleProvider({
5 clientId: process.env.GOOGLE_ID!,
6 clientSecret: process.env.GOOGLE_SECRET!,
7 }),
8],6ļøā£ **Client-Side Authentication Hooks**
1import { useSession, signIn, signOut } from "next-auth/react";
2
3export default function Navbar() {
4 const { data: session } = useSession();
5
6 return (
7 <nav>
8 {session ? (
9 <>
10 <p>Hello {session.user.name}</p>
11 <button onClick={() => signOut()}>Logout</button>
12 </>
13 ) : (
14 <button onClick={() => signIn()}>Login</button>
15 )}
16 </nav>
17 );
18}šÆ **Conclusion**: Auth.js is one of the most powerful and developer-friendly authentication libraries for Next.js. With minimal setup, it gives you secure credential login, OAuth support, JWT sessions, and full route protection across both server and client components. Itās an essential tool for building modern, secure full-stack applications.
