
이전 시간 카카오와 Supabase앱을 만들어 연동하였습니다.
⬇️ 이전 포스팅을 못보셨다면 아래로 이동하여 세팅을 먼저 해주세요! ⬇️
Next.js 환경에서 Supabase를 이용해 간단하게 카카오 로그인 구현하기 (1)
이번 시간에는 Next.js 환경에서 Supabase를 이용하여 아주 간단하게 카카오 로그인을 구현해 보려고 합니다! Supabase | The Open Source Firebase Alternative Build production-grade applications with a Postgres database, Authen
lurgi.tistory.com
이제 본격적으로 간단한 화면을 구현해 보겠습니다!
우선 Next App을 만들어 줍시다.
npx create-next-app@latest
1️⃣ Supabase 세팅
우선적으로 모듈을 다운로드 해줍시다.
npm i @supabase/auth-helpers-nextjs @supabase/supabase-js
React환경에서 사용하는 모듈 역시 다운로드 해줍시다.
npm i @supabase/auth-helpers-react
.env.local 파일을 생성한 후 Supabase 프로젝트의 정보를 입력해줍시다.
NEXT_PUBLIC_SUPABASE_URL=your-supabase-url
NEXT_PUBLIC_SUPABASE_ANON_KEY=your-supabase-anon-key
2️⃣ SessionContextProvider로 감싸주기
supabase/auth-helpers-react 모듈에서 제공하는 SessionContextProvider로 감싸주어야 합니다.
저는 SessionContextProvider를 이용하여 SupabaseProvider를 만들었고, 이를 감싸주었습니다,
// SupabaseProvider.tsx
"use client";
import { useState } from "react";
import { createClientComponentClient } from "@supabase/auth-helpers-nextjs";
import { SessionContextProvider } from "@supabase/auth-helpers-react";
interface SupabaseProviderProp {
children: React.ReactNode;
}
const SupabaseProvider: React.FC<SupabaseProviderProp> = ({ children }) => {
const [supabaseClient] = useState(() => createClientComponentClient());
return (
<SessionContextProvider supabaseClient={supabaseClient}>
{children}
</SessionContextProvider>
);
};
export default SupabaseProvider;
// Root layout.tsx
import type { Metadata } from "next";
import { Inter } from "next/font/google";
import "./globals.css";
import SupabaseProvider from "@/provider/SupabaseProvider";
const inter = Inter({ subsets: ["latin"] });
export const metadata: Metadata = {
title: "Create Next App",
description: "Generated by create next app",
};
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<body className={inter.className}>
<SupabaseProvider>{children}</SupabaseProvider> {/* Provider로 감싸줌*/}
</body>
</html>
);
}
이제 SupabaseProvider 내부에서 SupabaseClient를 사용할 수 있게 됩니다.
3️⃣ Auth페이지 만들기
Auth페이지를 간단하게 만들기 위해, 다음과 같은 모듈을 설치해줍시다
npm i @supabase/auth-ui-react @supabase/auth-ui-shared
저는 Auth페이지를 아래와 같이 간단히 만들어 보았습니다.
// app/auth/page.tsx
"use client";
import { useSupabaseClient } from "@supabase/auth-helpers-react";
import { Auth } from "@supabase/auth-ui-react";
import { ThemeSupa } from "@supabase/auth-ui-shared";
const SignIn = () => {
const supabaseClient = useSupabaseClient();
return (
<div className="h-full flex justify-center items-center">
<Auth
supabaseClient={supabaseClient}
appearance={{
theme: ThemeSupa,
style: { container: { width: "300px" } },
}} {/*CSS 커스텀 가능*/}
providers={["kakao"]} {/*카카오로 설정해주어야 함.*/}
localization={{}} {/*내부 글 커스텀 가능*/}
/>
</div>
);
};
export default SignIn;
이 코드를 통해 아래와 같은 깔끔한 로그인, 회원가입 페이지를 얻을 수 있게 됩니다!

정말 간단하게 로그인 페이지를 구현할 수 있었네요!
4️⃣ 로그인 된 정보 받아오기, 로그아웃 하기
로그인 이후 useUser()훅을 통해 간단하게 로그인된 정보를 받아올 수 있습니다.
그리고 createClientComponentClient()를 통해 로그아웃을 구현할 수 있습니다.
"use client";
import { useRouter } from "next/navigation";
import { useUser } from "@supabase/auth-helpers-react";
import { createClientComponentClient } from "@supabase/auth-helpers-nextjs";
const AuthContent = () => {
const supabase = createClientComponentClient(); //로그아웃 메서드를 받아오기 위해서 사용
const router = useRouter();
const user = useUser(); //useUser훅을 통해 유저데이터를 받아옴
const handleAuth = async () => {
if (user) {
const { error } = await supabase.auth.signOut(); //로그아웃
if (error) {
console.error(error);
}
}
if (!user) {
router.push("/auth");
}
};
return (
<div className="font-semibold h-full flex flex-col items-center justify-center">
{user && <div>안녕하세요 {user?.user_metadata.full_name}님</div>}
<div>
<button
className="border border-neutral-400 rounded-lg px-4 py-1 hover:bg-neutral-100 hover:border-neutral-500 transition"
onClick={handleAuth}>
{user ? "로그아웃" : "로그인"}
</button>
</div>
</div>
);
};
export default AuthContent;
다음 시간에는 카카오 로그인을 이용하여, 카카오 메세지를 보내는 방법을 포스팅 해보도록 하겠습니다!
src
Supabase Auth with the Next.js App Router | Supabase Docs
The getSession function must be called for any Server Component routes that use a Supabase client.
supabase.com
Auth UI | Supabase Docs
Currently there is only one predefined theme available, but we plan to add more.
supabase.com
'개발관련 > Next' 카테고리의 다른 글
Next.js 환경에서 cookie 설정하기 (1) | 2024.01.09 |
---|---|
Next.js 환경에서 Supabase를 이용해 간단하게 카카오 로그인 구현하기 (1) (0) | 2023.12.09 |
Next.js, Typescript 환경에서 라이브러리 “모듈에 대한 선언 파일을 찾을 수 없습니다” 에러 (0) | 2023.12.07 |
Next.js에서 Clerk.js 사용하여 구글 연동 로그인 만들기 (0) | 2023.11.16 |
[Next.js] 전역 객체, .env 타입 설정하기 (0) | 2023.10.09 |