[supabase] 세팅하기

설치

yarn add @supabase/ssr @supabase/supabse-js

 

 

환경변수 설정

.env.local 파일에 supabase 프로젝트 url과 api key를 추가해준다

 

 

설정파일 추가

utils/supabase/client.ts

import { createBrowserClient } from "@supabase/ssr";

export const createClient = () =>
  createBrowserClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!
  );

const browserClient = createClient();

export default browserClient;

 

utils/supabase/server.ts

import { createServerClient } from "@supabase/ssr";
import { cookies } from "next/headers";

export const createClient = () => {
  const cookieStore = cookies();

  return createServerClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
    {
      cookies: {
        getAll() {
          return cookieStore.getAll();
        },
        setAll(cookiesToSet) {
          try {
            cookiesToSet.forEach(({ name, value, options }) => {
              cookieStore.set(name, value, options);
            });
          } catch (error) {
            // The `set` method was called from a Server Component.
            // This can be ignored if you have middleware refreshing
            // user sessions.
          }
        },
      },
    }
  );
};

export const getIsLogin = async () => {
  const serverClient = createClient();
  const {
    data: { session },
  } = await serverClient.auth.getSession();
  return !!session;
};

 

utils/supabase/middleware.ts

import { createServerClient } from "@supabase/ssr";
import { type NextRequest, NextResponse } from "next/server";

export const updateSession = async (request: NextRequest) => {
  // This `try/catch` block is only here for the interactive tutorial.
  // Feel free to remove once you have Supabase connected.
  try {
    // Create an unmodified response
    let response = NextResponse.next({
      request: {
        headers: request.headers,
      },
    });

    const supabase = createServerClient(
      process.env.NEXT_PUBLIC_SUPABASE_URL!,
      process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
      {
        cookies: {
          getAll() {
            return request.cookies.getAll();
          },
          setAll(cookiesToSet) {
            cookiesToSet.forEach(({ name, value }) =>
              request.cookies.set(name, value)
            );
            response = NextResponse.next({
              request,
            });
            cookiesToSet.forEach(({ name, value, options }) =>
              response.cookies.set(name, value, options)
            );
          },
        },
      }
    );

    // This will refresh session if expired - required for Server Components
    // https://supabase.com/docs/guides/auth/server-side/nextjs
    await supabase.auth.getUser();

    return response;
  } catch (e) {
    // If you are here, a Supabase client could not be created!
    // This is likely because you have not set up environment variables.
    // Check out http://localhost:3000 for Next Steps.
    return NextResponse.next({
      request: {
        headers: request.headers,
      },
    });
  }
};

 

 

컴포넌트에서 사용하기

서버 컴포넌트

utils/supabse/server.ts에서 createClent()를 임포트해 serverClient 생성

supabase method들을 사용해 테이블에 접근할 수 있음

const serverClient = createClient();
const { data: supabaseData } = await serverClient.from('products').select();

console.log(supabaseData);  // products 테이블의 모든 데이터를 받아올 수 있음

 

* 이 때 RLS 설정을 해둔 경우 데이터를 받아올 수 없다

- 테이블 > Add RLS policy > create policy > 원하는 동작(select 등)에 대한 템플릿이 제공된다 필요한 것 선택해 추가!

 

 

Github 로그인 만들기

Github에서 OAuth app 생성

1) 내 깃허브 계정 > settings > developer settings > OAuth Apps > Register a new application

- Homepage URL은 우선 http://localhost:3000/

- Authorization callback URL에 supabase authentication > Providers > Github > GIthub enabled 활성화 > Callback URL 복붙하기

 

2) 생성 완료

 

3) Client ID와 Generate a new client secret > 생성된 키 복사하여 위의 supabase Auth provider > github > client secret에 붙여넣기

github

 

프로젝트에 추가하기

깃허브로 로그인하기 같은 버튼에 아래 함수를 온클릭으로 추가해 실행할 수 있게 함

async function signInWithGithub() {
  await browserClient.auth.signInWithOAuth({
    provider: 'github',
    options: {
      redirectTo: window.origin + '/auth/callback',
    }
  })
}

 

redirectTo 옵션 설정

1) supabase > Authentication > URL Configuration > Site URL 추가 (개발 단계에선 http://localhost:3000/ 넣어주면 됨)

2) /auth/callback 라우트핸들러 추가

- app/auth/callback/route.ts 추가

import { NextResponse } from 'next/server'
// The client you created from the Server-Side Auth instructions
import { createClient } from '@/utils/supabase/server'

export async function GET(request: Request) {
  const { searchParams, origin } = new URL(request.url)
  const code = searchParams.get('code')
  // if "next" is in param, use it as the redirect URL
  const next = searchParams.get('next') ?? '/'

  if (code) {
    const supabase = createClient()
    const { error } = await supabase.auth.exchangeCodeForSession(code)
    if (!error) {
      const forwardedHost = request.headers.get('x-forwarded-host') // original origin before load balancer
      const isLocalEnv = process.env.NODE_ENV === 'development'
      if (isLocalEnv) {
        // we can be sure that there is no load balancer in between, so no need to watch for X-Forwarded-Host
        return NextResponse.redirect(`${origin}${next}`)
      } else if (forwardedHost) {
        return NextResponse.redirect(`https://${forwardedHost}${next}`)
      } else {
        return NextResponse.redirect(`${origin}${next}`)
      }
    }
  }

  // return the user to an error page with instructions
  return NextResponse.redirect(`${origin}/auth/auth-code-error`)
}

 

인증 여부 확인

broswerClient.auth.getSession();

getSession을 활용해 session 정보를 확인할 수 있다.