next-auth와 카카오 로그인 연동

Dec 10, 2021

next-auth가 v4로 업데이트 되면서 기존 카카오 프로바이더 코드를 적용하면 돌아가지 않아서 정리해본다.

2022.04.10 기준 카카오 프로바이더도 업데이트가 되어서 추가 설정없이 적용할 수 있다.

install packages

npm i next-auth @next-auth/prisma-adapter

prisma/schema.prisma

enum Role {
  USER
  ADMIN
}

model User {
  id            String    @id @default(uuid())
  name          String?
  email         String?   @unique
  emailVerified DateTime?
  image         String?
  role          Role      @default(USER)
  accounts      Account[]
  sessions      Session[]
}

model Account {
  id                       String  @id @default(uuid())
  type                     String
  provider                 String
  providerAccountId        String
  userId                   String
  user                     User    @relation(fields: [userId], references: [id], onDelete: Cascade)
  refresh_token            String?
  refresh_token_expires_in Int?
  access_token             String?
  expires_in               Int?
  expires_at               Int?
  token_type               String?
  scope                    String?

  @@unique([provider, providerAccountId])
}

model Session {
  id           String   @id @default(uuid())
  sessionToken String   @unique
  expires      DateTime
  userId       String
  user         User     @relation(fields: [userId], references: [id], onDelete: Cascade)
}

~/helpers/prisma.ts

import { PrismaClient } from '@prisma/client';

declare global {
  // eslint-disable-next-line no-var
  var prisma: PrismaClient | undefined;
}

export const prisma = global.prisma || new PrismaClient();

if (process.env.NODE_ENV === 'development') global.prisma = prisma;

.env

# prisma
DATABASE_URL=

# next-auth
NEXTAUTH_URL=
# openssl rand -base64 32 등으로 적당히 생성한 값
SECRET=

# kakao
KAKAO_CLIENT_ID=
KAKAO_CLIENT_SECRET=

pages/api/auth/[...nextauth].ts

import { PrismaAdapter } from '@next-auth/prisma-adapter';
import NextAuth from 'next-auth';
import KakaoProvider from 'next-auth/providers/kakao';
import {
  KAKAO_CLIENT_ID,
  KAKAO_CLIENT_SECRET,
  SECRET,
} from '~/helpers/constants';
import { prisma } from '~/helpers/prisma';

export default NextAuth({
  providers: [
    KakaoProvider({
      clientId: KAKAO_CLIENT_ID,
      clientSecret: KAKAO_CLIENT_SECRET,
    }),
  ],
  adapter: PrismaAdapter(prisma),
  secret: SECRET,
  session: {
    strategy: 'jwt',
    maxAge: 30 * 24 * 60 * 60, // 30 days
    updateAge: 24 * 60 * 60, // 24 hours
  },
  jwt: {
    secret: SECRET,
  },
  pages: {
    signIn: '/auth/signin', // 로그인 페이지
  },
  callbacks: {
    async jwt({ token, user }) {
      if (user) {
        token.role = user.role;
      }
      return token;
    },
    async session({ session, token }) {
      session.role = token.role;
      return session;
    },
  },
});

이 패키지 덕분에 Next.js에서 카카오 로그인을 쉽게 해결할 수 있었다.

Copyright © 2022nana