공식사이트: https://next-auth.js.org/
npm install next-auth
next-auth는 NextJS의 동적 API route를 이용해 로그인을 구현한다.
동적 API route는 Server-Side에서 동작하는 코드로 사용자가 RESTful하게 요청과 응답을 구성할 수 있는 라우팅 방식이다.
동적 route를 지원하기 때문에, 다양한 경로의 API 요청을 동적으로 구성할 수 있다.
NextJS v13 이후 app/api/auth/[...nextauth]
폴더 밑에 route.js 또는 route.ts 파일로 작성한다.
next-auth 같이 API를 이용하려면 route.js 파일이름을 사용해야 한다.
next-auth에서 제공하는 signIn/signOut 함수 역시 이 api로 요청을 보내는 것이다. e.g api/auth/signIn/Kakao, api/auth/signOut
// app/api/auth/[...nextauth]/route.ts
import NextAuth from "next-auth"
const handler = NextAuth( //NextAuth.js를 사용하여 인증과 관련된 작업을 처리하는 핵심 함수이다.
{...})
export { handler as GET, handler as POST }
{...} 부분에 구글 로그인 Provider를 구현한다.
참고: https://next-auth.js.org/providers/google
import NextAuth from "next-auth"
import GoogleProvider from "next-auth/providers/google";
const handler = NextAuth({
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID || "", // clientId가 항상 string이어야 한다.
clientSecret: process.env.GOOGLE_CLIENT_SECRET || "",
}),
],
});
export { handler as GET, handler as POST };
발급받은 후 clientId, clientSecret 환경변수를 읽어오기 위해 폴더의 최상위에서 .env.local 파일을 만든다.
GOOGLE_CLIENT_ID = 구글에서 받은 아이디
GOOGLE_CLIENT_SECRET = 구글에서 받은 키
로그인한 사용자 정보를 가지고 있는 context를 만든다.
context안에 SessionProvider가 실제 로그인한 데이터를 가지고 있다.
"use client";
// next에서 context를 사용하기 위해서는 csr 렌더링으로 명시해주어야 한다.
// context는 상태를 가지고 있기 때문에, 서버컴포넌트는 상태에 접근 할 수 없다.
import { SessionProvider } from "next-auth/react";
type Props = {
children:React.ReactNode;
}
export default function AuthContext({ children }: Props) {
return <SessionProvider>{children}</SessionProvider>;
}
Session Provider?
로그인에 대한 세션 정보를 얻어오기 위해서 Session Provider를 사용한다. 또한 세션 정보를 접근하기 위해서는 useSession이라는 리액트 훅을 사용해야 접근이 가능하다.
<AuthContext>
추가자식컴포넌트를 <AuthContext></AuthContext>
로 감싼다.
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en" className={openSans.className}>
<body className="w-full max-w-screen-xl overflow-auto mx-auto">
<AuthContext>
<header className="sticky top-0 bg-white z-10 border-b">
<Navbar />
</header>
<main className="px-6">{children}</main>
</AuthContext>
</body>
</html>
);
}
const { data: session } = useSession()
useSession 훅을 사용해서 로그인 정보를 가져온다.
providers
secret
callback
pages
signIn, signOut, error page 등 custom할 때 사용한다.
NextAuth({
providers: [
...
],
secret: process.env.AUTH_SECRET,
callbacks: {
async session({ session }) {
return session
},
async signIn({ profile }) {
...
return true
...
return false
},
pages: {
signIn: '/signin'
}
});