Supabase 프로젝트 생성시 필수 설정 요소

황유빈·2024년 10월 22일

환경 변수 설정

  1. .env 파일 생성 후
  2. 프로젝트 환경 설정에 나와있음
  3. DB_PASSWORD 는 프로젝트 생성 할 때 만든 그 패스워드임 절대 공개 하면 안됌 ,SERVICE_ROL도 마찬가지
NEXT_PUBLIC_SUPABASE_URL=프로젝트 url
NEXT_PUBLIC_SUPABASE_ANON_KEY=
NEXT_SUPABASE_SERVICE_ROLE=
NEXT_SUPABASE_DB_PASSWORD=

알맞은 값 입력

types_db.ts 생성

"scripts": {
  "generate-types": "npx supabase gen types typescript --project-id [project_id] --schema public > types_db.ts"
}

package.json 파일에 명령어 설치

Supabase 프로젝트의 데이터베이스 스키마를 기반으로 TypeScript 타입 파일을 자동으로 생성하고, 그 결과를 types_db.ts 파일에 저장하는 역할을 함
그리고

npm run generate-types 

실행 시켜주면 types.db 를 생성 됌

연동

npx supabase login

이거 입력해주면 supabse 프로젝트랑 로컬이랑 연동 끝임
types.db 파일 보면 내용이 채워져있음

SSR 프로젝트로 하고싶으면?

npm install @supabase/ssr @supabase/supabase-js

클라이언트,서버, 미들웨어 설정

client.ts

  • 목적: 브라우저 환경에서 Supabase 클라이언트를 생성하기 위한 함수
  • 주요 기능:
    createBrowserSupabaseClient(): 브라우저에서 사용할 Supabase 클라이언트를 생성함. Supabase의 URL과 익명 키를 환경 변수에서 읽어옴.
"use client";

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

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

server.ts

  • 목적: 서버 환경에서 Supabase 클라이언트를 생성하기 위한 함수들
  • 주요 기능:
    • createServerSupabaseClient(): 서버에서 사용할 Supabase 클라이언트를 생성합니다. 환경 변수에서 Supabase의 URL과, 주어진 권한에 따라 비공식 또는 관리 권한 키를 사용함. 쿠키 관리 기능도 포함되어 있음.
    • createServerSupabaseAdminClient(): 관리 권한을 가진 Supabase 클라이언트를 생성함. 서버 측에서만 호출되며, admin 플래그를 true로 설정하여 관리 키를 사용함

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

export const createServerSupabaseClient = async (cookieStore: ReturnType<typeof cookies> = cookies(), admin: boolean = false) => {
    return createServerClient<Database>(process.env.NEXT_PUBLIC_SUPABASE_URL!, admin ? process.env.NEXT_SUPABASE_SERVICE_ROLE! : process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!, {
        cookies: {
            get(name: string) {
                return cookieStore.get(name)?.value;
            },
            set(name: string, value: string, options: CookieOptions) {
                try {
                    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.
                }
            },
            remove(name: string, options: CookieOptions) {
                try {
                    cookieStore.set({ name, value: "", ...options });
                } catch (error) {
                    // The `delete` method was called from a Server Component.
                    // This can be ignored if you have middleware refreshing
                    // user sessions.
                }
            },
        },
    });
};

export const createServerSupabaseAdminClient = async (cookieStore: ReturnType<typeof cookies> = cookies()) => {
    return createServerSupabaseClient(cookieStore, true);
};

middleware.ts

  • 목적: Next.js 애플리케이션에서 요청 및 응답을 처리하고 Supabase 클라이언트를 적용하기 위한 미들웨어
  • 주요 기능:
    • applyMiddlewareSupabaseClient(): 요청을 처리하며 Supabase 클라이언트를 생성하고, 쿠키를 관리합니다. 요청과 응답에 Supabase 클라이언트를 통합하고 인증 토큰을 갱신함.
    • middleware(): applyMiddlewareSupabaseClient()를 호출하여 미들웨어를 구현함. 특정 요청 경로에 대해 미들웨어가 동작하도록 설정함.
import { type NextRequest, NextResponse } from "next/server";

export const applyMiddlewareSupabaseClient = async (request: NextRequest) => {
  // 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: {
        get(name: string) {
          return request.cookies.get(name)?.value;
        },
        set(name: string, value: string, options: CookieOptions) {
          // If the cookie is updated, update the cookies for the request and response
          request.cookies.set({
            name,
            value,
            ...options,
          });
          response = NextResponse.next({
            request: {
              headers: request.headers,
            },
          });
          response.cookies.set({
            name,
            value,
            ...options,
          });
        },
        remove(name: string, options: CookieOptions) {
          // If the cookie is removed, update the cookies for the request and response
          request.cookies.set({
            name,
            value: "",
            ...options,
          });
          response = NextResponse.next({
            request: {
              headers: request.headers,
            },
          });
          response.cookies.set({
            name,
            value: "",
            ...options,
          });
        },
      },
    }
  );

  // refreshing the auth token
  await supabase.auth.getUser();

  return response;
};

export async function middleware(request) {
  return await applyMiddlewareSupabaseClient(request);
}

export const config = {
  matcher: [
    /*
     * Match all request paths except for the ones starting with:
     * - _next/static (static files)
     * - _next/image (image optimization files)
     * - favicon.ico (favicon file)
     * Feel free to modify this pattern to include more paths.
     */
    "/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)",
  ],
};

0개의 댓글