/**
* Supabase Admin Client (Server-side only)
*
* Uses lazy initialization via Proxy to avoid errors during Next.js build time
* when environment variables are not available.
*/
import { createClient, SupabaseClient } from '@supabase/supabase-js';
let supabaseAdmin: SupabaseClient | null = null;
/**
* Get the Supabase admin client with service role key.
* Lazy initialization ensures it only runs at request time, not build time.
*/
export function getSupabaseAdmin(): SupabaseClient {
if (!supabaseAdmin) {
const url = process.env.NEXT_PUBLIC_SUPABASE_URL;
const key = process.env.SUPABASE_SERVICE_ROLE_KEY;
if (!url || !key) {
throw new Error('Supabase credentials not configured');
}
supabaseAdmin = createClient(url, key);
}
return supabaseAdmin;
}
/**
* Lazy proxy for supabase admin client.
* Can be imported directly as `supabase` and will initialize on first use.
*/
export const supabase = new Proxy({} as SupabaseClient, {
get(_, prop) {
return getSupabaseAdmin()[prop as keyof SupabaseClient];
},
});