Next.js에서 카카오, 네이버 로그인을 가장 쉽게 구현하는 방법.
- 카카오/네이버 provider 내장 - 복잡한 OAuth 설정 없이 바로 사용
- 공식 디자인 버튼 - 각 서비스 가이드라인 준수
- 한국어 에러 메시지 - 문제 원인과 해결 방법을 바로 확인
- next-auth 호환 - 구글, 애플, GitHub 등 함께 사용 가능
npm install @relkimm/k-auth// auth.ts
import { KAuth } from '@relkimm/k-auth';
export const { handlers, auth, signIn, signOut } = KAuth({
kakao: {
clientId: process.env.KAKAO_CLIENT_ID!,
clientSecret: process.env.KAKAO_CLIENT_SECRET!,
},
naver: {
clientId: process.env.NAVER_CLIENT_ID!,
clientSecret: process.env.NAVER_CLIENT_SECRET!,
},
});// app/api/auth/[...nextauth]/route.ts
import { handlers } from '@/auth';
export const { GET, POST } = handlers;import { Button } from '@relkimm/k-auth/ui';
import { signIn } from '@/auth';
<Button.Group>
<Button.Kakao onClick={() => signIn('kakao')} />
<Button.Naver onClick={() => signIn('naver')} />
</Button.Group>// app/page.tsx
import { auth } from '@/auth';
export default async function Page() {
const session = await auth();
if (!session) {
return <a href="/login">로그인</a>;
}
return <p>안녕하세요, {session.user?.name}님!</p>;
}// 지원 버튼
<Button.Kakao />
<Button.Naver />
<Button.Google />
<Button.Apple />
// 크기
<Button.Kakao size="sm" />
<Button.Kakao size="lg" />
<Button.Kakao size="icon" />
// 그룹
<Button.Group direction="row" gap="md">
<Button.Kakao size="icon" />
<Button.Naver size="icon" />
</Button.Group>KAuth({
kakao: {
clientId: '...',
clientSecret: '...',
collectPhone: true, // 전화번호
collectBirth: true, // 생년월일
collectGender: true, // 성별
},
});import Google from 'next-auth/providers/google';
import Apple from 'next-auth/providers/apple';
KAuth({
kakao: { ... },
naver: { ... },
nextAuthConfig: {
providers: [
Google({ clientId: '...', clientSecret: '...' }),
Apple({ clientId: '...', clientSecret: '...' }),
],
},
});// middleware.ts
import { auth } from '@/auth';
export default auth((req) => {
if (!req.auth && req.nextUrl.pathname !== '/login') {
return Response.redirect(new URL('/login', req.nextUrl));
}
});
export const config = {
matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'],
};KAKAO_CLIENT_ID=
KAKAO_CLIENT_SECRET=
NAVER_CLIENT_ID=
NAVER_CLIENT_SECRET=
AUTH_SECRET= # openssl rand -base64 32자세한 사용법은 문서 사이트를 참고하세요.
- Next.js 14+
- React 18+
MIT