Next.js에서 SSR + 인증을 구현할 때, next-auth는 가장 널리 사용되는 인증 라이브러리 중 하나입니다.

특히, 브라우저의 쿠키를 이용해 세션을 자동 관리해주며, 내부적으로는JWT 기반 또는 서버 세션(DB 저장) 기반 중 선택할 수 있도록 유연하게 구성되어 있어 실무에서 매우 유용하게 사용됩니다.

next-auth 개요


✅ next-auth 인증 흐름 요약 (쿠키 기반)

[1] 로그인 페이지 → 자격 정보 입력 (이메일/비번 또는 OAuth)
[2] /api/auth/callback 호출 → 인증 성공 시 세션 생성
[3] 브라우저에 쿠키 저장 (session token 포함)
[4] 이후 요청 시 자동으로 쿠키 포함 → 서버가 세션 확인 후 사용자 정보 반환

✅ 1. 기본 설치 및 설정

npm install next-auth

✅ 2. 파일 구조 (App Router 기준)

/app
  /api
    /auth
      [...nextauth]/route.ts     ← API 라우트 (next-auth의 핵심)
  /login/page.tsx                ← 로그인 UI


✅ 3. app/api/auth/[...nextauth]/route.ts

// /app/api/auth/[...nextauth]/route.ts
import NextAuth from "next-auth"
import CredentialsProvider from "next-auth/providers/credentials"

const handler = NextAuth({
  providers: [
    CredentialsProvider({
      name: "Credentials",
      credentials: {
        email: {},
        password: {}
      },
      async authorize(credentials) {
        const user = await fetchUser(credentials.email, credentials.password)
        if (user) return user
        return null
      }
    })
  ],
  session: {
    strategy: "jwt", // 또는 "database" (세션 방식)
  },
  secret: process.env.NEXTAUTH_SECRET,
})

export { handler as GET, handler as POST }