복잡한뇌구조마냥

[Next.js] Supabase 연동하기 본문

FE/Next.js

[Next.js] Supabase 연동하기

지금해냥 2025. 7. 14. 16:53

📌 개요

지난 글에서는 Supabase에 댓글 테이블을 만들고 인증 유저와의 외래 키도 연결해보았습니다.
이번 글에서는 Next.js에서 Supabase를 연동해 데이터 정보를 조회하는 방법을 소개합니다.


1️⃣ Supabase JS SDK 설치

npm install @supabase/supabase-js

2️⃣ 환경 변수 설정 (.env.local)

// .env.local
NEXT_PUBLIC_SUPABASE_URL=https://your-project-id.supabase.co
NEXT_PUBLIC_SUPABASE_ANON_KEY=your-anon-key

🔐 주의

  • NEXT_PUBLIC_ prefix는 브라우저에서 사용 가능함
  • **서비스 키(service_role)**는 절대 클라이언트에 쓰지 말 것 (노출 안되게 할 것)

3️⃣ Supabase 클라이언트 생성 (lib/supabase.ts)

// lib/supabaseClient.ts
import { createClient } from '@supabase/supabase-js';

const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL!;
const supabaseAnonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!;

export const supabase = createClient(supabaseUrl, supabaseAnonKey);

4️⃣ 댓글 데이터 조회 함수 작성

import { supabase } from "@/lib/supabase";

export interface Comment {
  id: number;
  created_date: string;
  modified_date: string;
  content: string;
  post_id: number;
  user_id: string;
}

export interface CommentWithUser extends Comment {
  user: { email: string } | null;
}

// 댓글 목록
export async function getCommentsByPost(
  postId: number
): Promise<CommentWithUser[]> {
  const { data, error } = await supabase
    .from("comments")
    .select("*")
    .eq("post_id", postId)
    .order("created_date", { ascending: true });
  if (error) return [];
  return data || [];
}

5️⃣ 컴포넌트에서 불러와서 렌더링

// 댓글 불러오기
  useEffect(() => {
    const fetchComments = async () => {
      if (!params.id) return;
      const data = await getCommentsByPost(Number(params.id));
      setComments(data);
    };
    fetchComments();
  }, [params.id]);

6️⃣ 데이터 불러오기 예시


7️⃣ 마무리

Supabase와 Next.js만으로도 복잡한 API 없이 빠르게 게시글 및 댓글 시스템을 만들 수 있습니다.
Supabase 설정에서 보안 규칙(Row Level Security)을 설정하셨다면 인증된 사용자만 작성 가능하도록 제한도 가능합니다.

🛠️ Supabase CRUD API는 공식 문서에서 쉽게 확인할 수 있어요

이번 글에서는 게시글 & 댓글 데이터를 조회(read)하는 기능을 다뤘지만,
Supabase는 insert, update, delete 등 CRUD API를 모두 지원합니다.

// 댓글 추가
await supabase.from("comments").insert([
  { content: "좋은 글이네요!", post_id, user_id },
]);

// 댓글 수정
await supabase.from("comments").update({ content: "수정된 내용" }).eq("id", commentId);

// 댓글 삭제
await supabase.from("comments").delete().eq("id", commentId);

 

더 다양한 예제는 공식 문서를 참고해보세요:
🔗 Supabase JS Client Docs – CRUD
 

📚 참고 자료

LIST