Next.js에서 NextAuth를 활용하여 간편한 인증 시스템을 구축할 수 있습니다.
이 글에서는 NextAuth 설치부터 API 라우트 설정, 클라이언트 사용 방법까지 한 번에 정리해 보겠습니다.
npm install next-auth
NextAuth를 설치한 후, API 라우트를 설정해야 합니다.
src/app/api/auth/[...nextauth]/route.ts
파일을 생성하고 다음과 같이 설정합니다.
이 파일에서 **인증 프로바이더(Providers)**와 **콜백(Callbacks)**을 정의할 수 있습니다.
import NextAuth, { NextAuthOptions } from 'next-auth';
import CredentialsProvider from 'next-auth/providers/credentials';
import { fetchSignIn, fetchUser } from '@/app/api/auth';
const handler = NextAuth({
providers: [
CredentialsProvider({
id: 'credentials',
name: 'Credentials',
credentials: {
email: { label: 'Email', type: 'text', placeholder: '[email protected]' },
password: { label: 'Password', type: 'password' },
},
async authorize(credentials) {
const { data: { access_token } } = await fetchSignIn({
email: credentials?.email || '',
password: credentials?.password || '',
});
const user = await fetchUser();
const id = access_token.split('|')[0] || '';
return user ? { ...user.data, id } : null;
},
}),
],
callbacks: {
async jwt({ token, user, trigger }) {
if (trigger === 'update') {
const updateUser = await fetchUser();
return { ...token, ...user, ...updateUser.data };
}
return { ...token, ...user };
},
async session({ session, token }) {
session.user = token as never;
return session;
},
},
pages: { signIn: '/signin' },
} as NextAuthOptions);
export { handler as GET, handler as POST };
📌 핵심 기능 정리