Next.js에서 SSR + 인증을 구현할 때, next-auth는 가장 널리 사용되는 인증 라이브러리 중 하나입니다.
특히, 브라우저의 쿠키를 이용해 세션을 자동 관리해주며, 내부적으로는JWT 기반 또는 서버 세션(DB 저장) 기반 중 선택할 수 있도록 유연하게 구성되어 있어 실무에서 매우 유용하게 사용됩니다.
next-auth 개요/app)와 Pages Router (/pages) 모두 지원[1] 로그인 페이지 → 자격 정보 입력 (이메일/비번 또는 OAuth)
[2] /api/auth/callback 호출 → 인증 성공 시 세션 생성
[3] 브라우저에 쿠키 저장 (session token 포함)
[4] 이후 요청 시 자동으로 쿠키 포함 → 서버가 세션 확인 후 사용자 정보 반환
npm install next-auth
/app
/api
/auth
[...nextauth]/route.ts ← API 라우트 (next-auth의 핵심)
/login/page.tsx ← 로그인 UI
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 }