Next.js 15 Full-Stack Application Development

Ders 2/3 45 dakika

Authentication with NextAuth.js v5

Auth.js setup, Google/GitHub OAuth, credentials provider and session management.

What is Auth.js v5?

Formerly known as NextAuth.js, Auth.js is the go-to authentication library for Next.js. It supports OAuth (Google, GitHub, Twitter), credentials (email+password) and magic links.

Installation

npm install next-auth@beta
openssl rand -base64 32  # generate AUTH_SECRET
# .env.local
AUTH_SECRET="value-from-openssl"
AUTH_GOOGLE_ID="your-google-client-id"
AUTH_GOOGLE_SECRET="your-google-client-secret"
AUTH_GITHUB_ID="your-github-client-id"
AUTH_GITHUB_SECRET="your-github-client-secret"

Auth Configuration

// auth.ts (at project root)
import NextAuth from "next-auth";
import Google from "next-auth/providers/google";
import GitHub from "next-auth/providers/github";
import Credentials from "next-auth/providers/credentials";
import { prisma } from "@/lib/prisma";
import bcrypt from "bcryptjs";

export const { handlers, auth, signIn, signOut } = NextAuth({
  providers: [
    Google,
    GitHub,
    Credentials({
      credentials: {
        email: { label: "Email", type: "email" },
        password: { label: "Password", type: "password" },
      },
      async authorize(credentials) {
        const { email, password } = credentials as { email: string; password: string };
        const user = await prisma.user.findUnique({ where: { email } });

        if (!user || !user.passwordHash) return null;

        const match = await bcrypt.compare(password, user.passwordHash);
        return match ? user : null;
      },
    }),
  ],
  callbacks: {
    async session({ session, token }) {
      if (session.user && token.sub) {
        session.user.id = token.sub;
        session.user.role = token.role as string;
      }
      return session;
    },
    async jwt({ token, user }) {
      if (user) token.role = (user as any).role;
      return token;
    },
  },
  pages: {
    signIn: "/login",
    error: "/login/error",
  },
});

Create the Route Handler

// app/api/auth/[...nextauth]/route.ts
import { handlers } from "@/auth";
export const { GET, POST } = handlers;

Accessing the Session

// Server Component
import { auth } from "@/auth";

export default async function Dashboard() {
  const session = await auth();
  if (!session) return <p>Please log in</p>;
  return <h1>Welcome, {session.user?.name}!</h1>;
}

// Client Component
"use client";
import { useSession } from "next-auth/react";

export default function UserInfo() {
  const { data: session, status } = useSession();
  if (status === "loading") return <p>Loading...</p>;
  if (!session) return <p>Not logged in</p>;
  return <p>Hello, {session.user?.name}!</p>;
}

Middleware Protection

// middleware.ts
import { auth } from "@/auth";

export default auth((req) => {
  if (!req.auth && req.nextUrl.pathname.startsWith("/dashboard")) {
    return Response.redirect(new URL("/login", req.url));
  }
});

export const config = { matcher: ["/dashboard/:path*"] };

Önemli Noktalar

  • Auth.js supports OAuth and credentials providers
  • auth.ts defines providers and callbacks
  • Use auth() in Server Components, useSession() in Client Components
  • Middleware provides route-level session protection