개발로 부자되기/next.js

next 13 auth firebase google login 해결법 (vercel 배포까지)

야나부짱 2023. 9. 29. 13:14

https://www.telerik.com/blogs/how-to-implement-google-authentication-nextjs-app-using-nextauth

 

How to Implement Google Authentication in Next with NextAuth

This article demonstrates how to incorporate single sign-on using OAuth protocol in a Next.js application via the NextAuth module with Google authentication.

www.telerik.com

이 글을 따라하면 잘 됩니다.

 

firebase login을 연동하는 방법이 server기반 (firebase-admin)을 활용하는 방식과 next-auth를 사용하는 방식 2가지가 있는데, next-auth가 좀더 편한거 같아서 저는 요거로 해봅니다.

 

하기전에 next version도 잘 체크하세요. 제 next, next-auth version은 아래와 같습니다.

"next": "13.3",
"next-auth": "^4.20.1",
 

 

1. Registering Our App and Getting OAuth Credentials

oauth credentials를 발급받는다.

 

https://console.cloud.google.com/apis/credentials/oauthclient

 

Google 클라우드 플랫폼

로그인 Google 클라우드 플랫폼으로 이동

accounts.google.com

Authorized JavaScript origins

http://localhost:3000

Authorized redirect URIs

http://localhost:3000/api/auth/callback/google

 

코드

아래 코드는 app/api/auth/[...nextauth]/route.js에 넣는 코드입니다. 백앤드에 해당하는 코드로 볼 수 있죠.

import NextAuth from 'next-auth';
import GoogleProvider from 'next-auth/providers/google';
export const authOptions = {
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
}),
],
session: {
strategy: 'jwt',
},
};
const handler = NextAuth(authOptions);

export { handler as GET, handler as POST }

 

다음은 front end code입니다.

 

아래처럼 authsession을 하나의 컴포넌트로 구성하고요,

'use client';
import { SessionProvider } from "next-auth/react";


export default function AuthSession({ children }) {
return <SessionProvider>{children}</SessionProvider>;
}

프론트코드는 일단 app/layout.js에 상위로 둘러야합니다.

import { Provider } from "react-redux";
import store from "../store";
import AuthSession from "@/components/AuthSession";

export default function RootLayout({ children }) {
return (
<>
<html lang="en">
<body className="font-inter custom-tippy dashcode-app">
<AuthSession>
<Provider store={store}>{children}</Provider>
</AuthSession>
</body>
</html>
</>
);
}

 

page에서는 아래처럼 불러옵니다.

 

"use client";

import { useSession, signIn, signOut } from "next-auth/react"
export default function Component() {

const { data } = useSession()
if (data) {
console.log('data', data)
return (
<>
Signed in as {data.user.name} <br />
<button onClick={() => signOut()}>Sign out</button>
</>
)
}
return (
<>
Not signed in <br />
<button onClick={() => signIn('google')}>Sign in</button>
</>
)
}

 

 

설정

설정도 중요한데, .env도 잘 채워줘야합니다. 이건 local에서 사용합니다. vercel로 배포하는 경우, environment variables 환경변수를 .env 대신 채워줍니다.

 

GOOGLE_CLIENT_ID=**
GOOGLE_CLIENT_SECRET=**
NEXTAUTH_URL=**
NEXTAUTH_SECRET=**