기록

개발모드에서 Supabase Service Role Key 임시 사용하기 본문

TIL*

개발모드에서 Supabase Service Role Key 임시 사용하기

mnmhbbb 2024. 8. 17. 15:34

사이드 프로젝트의 로그인 기능을 아직 구현하지 않은 상황이었다.
간단하게 Supabase를 사용하여 기능 테스트하기 위해
Supabase 서비스 역할 키(Service Role Key)를 사용하여 RLS(Row Level Security)정책을 일시적으로 비활성화 한 기록

테스트 할 table의 Enable Row Level Security (RLS) 을 체크해제 하는 방법도 있고, 더 간단하지만, 
다른 방법도 알게 되어 정리함.

 

Next.js + Supabase

0. Supabase 프로젝트 및 테스트 테이블 생성

1. Project Settings > API > Project API Keys > service_role을 .env에 가져온다.

NEXT_PUBLIC_SUPABASE_URL=https://...
NEXT_PUBLIC_SUPABASE_ANON_KEY=eyJ...
SUPABASE_SERVICE_ROLE_KEY=eyJ...

 

2. utils/supabase/server.ts

공식 문서의 코드를 가져 온 다음, useServiceRole 파라미터와 supabaseKey 부분만 수정한다.

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

export function createClient(useServiceRole = false) {
  const cookieStore = cookies();

  const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL!;
  const supabaseKey = useServiceRole
    ? process.env.SUPABASE_SERVICE_ROLE_KEY!
    : process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!;

  // Create a server's supabase client with newly configured cookie,
  // which could be used to maintain user's session
  return createServerClient(supabaseUrl, supabaseKey, {
    cookies: {
      getAll() {
        return cookieStore.getAll();
      },
      setAll(cookiesToSet) {
        try {
          cookiesToSet.forEach(({ name, value, options }) => cookieStore.set(name, value, options));
        } catch {
          // The `setAll` method was called from a Server Component.
          // This can be ignored if you have middleware refreshing
          // user sessions.
        }
      },
    },
  });
}

 

3. API 라우트에서 다음과 같이 supabase 사용

import { createClient } from "@/utils/supabase/server";
import { NextRequest, NextResponse } from "next/server";

export async function POST(req: NextRequest) {
  try {
    const subscription = await req.json();

    const supabase = createClient(true);

    const { data, error } = await supabase
      .from("user")
      .insert([
        {
          id: crypto.randomUUID(),
          created_at: new Date().toISOString(),
          subscription,
        },
      ])
      .select();

    if (error) {
      console.error("Supabase error:", error);
      return NextResponse.json({ message: error.message }, { status: 400 });
    } else {
      return NextResponse.json({ message: "success", data }, { status: 200 });
    }
  } catch (error) {
    console.error("Unexpected error:", error);
    return NextResponse.json({ message: "An unexpected error occurred" }, { status: 500 });
  }
}

 

위 방법을 사용하면 임시로 RLS 정책에 걸리지 않게 DB 데이터 삽입이 가능해진다.

Comments