supabase 연동을 위한 기본적인 준비
설치
npm install @supabase/supabase-js
npm install @supabase/ssr
supabase 클라이언트 라이브러리와 Next.js를 위한 패키지를 설치한다.
.env.local 설정
// .env.local
NEXT_PUBLIC_SUPABASE_URL=YOUR_SUPABASE_URL
NEXT_PUBLIC_SUPABASE_ANON_KEY=YOUR_SUPABASE_ANON_KEY
.env.local 파일에 SUPABASE_URL, SUPABASE_ANON_KEY 환경변수를 저장한다.
이 키들은 vercel 내 프로젝트 - Project Settings - Environment Variables 에서 볼 수 있다.
utils/supabase 위치에 client.ts, server.ts 생성
client-side Supabase and server-side Supabase를 위한 client.ts와 server.ts를 생성한다.
// utils/supabase/client.ts
import { createBrowserClient } from '@supabase/ssr'
export function createClient() {
// Create a supabase client on the browser with project's credentials
return createBrowserClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!
)
}
➭ 클라이언트 환경(CSR)에서 Supabase 인스턴스를 생성
// utils/supabase/server.ts
import { createServerClient } from '@supabase/ssr'
import { cookies } from 'next/headers'
export async function createClient() {
const cookieStore = await cookies()
// Create a server's supabase client with newly configured cookie,
// which could be used to maintain user's session
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 {
// The `setAll` method was called from a Server Component.
// This can be ignored if you have middleware refreshing
// user sessions.
}
},
},
}
)
}
➭ 서버 환경(SSR)에서 Supabase 인스턴스를 생성
➭ cookies를 활용한 세션 유지 가능
데이터 가져오기
// page.tsx
import { createClient } from '@/utils/supabase/server';
export default async function Home() {
const supabase = await createClient();
const { data: regions } = await supabase.from('regions').select();
return (
<div className="m-10">
<pre>{JSON.stringify(regions, null, 2)}</pre>
</div>
);
}
➭ regions 테이블에서 모든 데이터 조회
➭ data에 해당 결과 저장
결과 화면

데이터가 제대로 출력되는 걸 볼 수 있다.
⬇ 이 과정에서 발생한 에러 (빈 배열 출력)
[Next.js + supabase 연동] 데이터 가져오기 에러 - 빈 데이터
➜ 현재 상태 ✅ Next.js + vercel 배포 + supabase db 연결✅ 테이블 생성, 데이터 삽입 완료 이후 특정 데이터를 가져오는 과정에서 계속 빈 데이터를 가져오는 에러가 발생했다.코드 상 문제인 줄 알
gumsodev.tistory.com
참고
Build a User Management App with Next.js | Supabase Docs
Learn how to use Supabase in your Next.js App.
supabase.com
'Next.js' 카테고리의 다른 글
| [Next.js + Naver Map API] 보이는 지도 영역의 마커만 표시하기 (Typescript) (0) | 2025.02.24 |
|---|---|
| [Next.js] Supabase PostGIS로 거리순 데이터 정렬하기 (1) | 2025.02.24 |
| [Next.js + Naver Map API] 네이버 지도 api 사용하기ㅣ현재 위치, 주소 가져오기, 마커 표시하기 (0) | 2025.02.17 |
| [Next.js] Supabase 타입 Type 설정과 적용 (0) | 2025.02.14 |
| [Next.js 폰트 최적화] 로컬 폰트 Local Font 적용 (0) | 2025.01.17 |