From 3f30fbe89cade945b94a9ba70824cb838ccc9ec1 Mon Sep 17 00:00:00 2001 From: maulanasdqn Date: Wed, 21 Jan 2026 20:41:28 +0700 Subject: [PATCH] fix: make Supabase client lazy to avoid errors when credentials missing --- libs/service/src/supabase/client.ts | 51 ++++++++++++++++++++--------- 1 file changed, 35 insertions(+), 16 deletions(-) diff --git a/libs/service/src/supabase/client.ts b/libs/service/src/supabase/client.ts index cb5166e..7abc97e 100644 --- a/libs/service/src/supabase/client.ts +++ b/libs/service/src/supabase/client.ts @@ -1,24 +1,39 @@ -import { createClient } from '@supabase/supabase-js'; +import { createClient, SupabaseClient } from '@supabase/supabase-js'; const supabaseUrl = import.meta.env.VITE_SUPABASE_URL; const supabaseAnonKey = import.meta.env.VITE_SUPABASE_ANON_KEY; -if (!supabaseUrl || !supabaseAnonKey) { - throw new Error('Missing Supabase environment variables'); -} +// Lazy initialization - only create client when credentials are available +let _supabase: SupabaseClient | null = null; -// Create Supabase client with proper session management enabled -export const supabase = createClient(supabaseUrl, supabaseAnonKey, { - auth: { - autoRefreshToken: true, // ✅ Auto-refresh expired tokens - persistSession: true, // ✅ Persist session in storage - detectSessionInUrl: true, // ✅ Auto-detect OAuth callback - storage: typeof window !== 'undefined' ? window.localStorage : undefined, - }, - global: { - headers: { - 'X-Client-Info': 'supabase-js-web', - }, +const getSupabaseClient = (): SupabaseClient => { + if (!supabaseUrl || !supabaseAnonKey) { + throw new Error('Missing Supabase environment variables. Please set VITE_SUPABASE_URL and VITE_SUPABASE_ANON_KEY.'); + } + + if (!_supabase) { + _supabase = createClient(supabaseUrl, supabaseAnonKey, { + auth: { + autoRefreshToken: true, + persistSession: true, + detectSessionInUrl: true, + storage: typeof window !== 'undefined' ? window.localStorage : undefined, + }, + global: { + headers: { + 'X-Client-Info': 'supabase-js-web', + }, + }, + }); + } + + return _supabase; +}; + +// Export a proxy that lazily initializes the client +export const supabase = new Proxy({} as SupabaseClient, { + get(_, prop) { + return getSupabaseClient()[prop as keyof SupabaseClient]; }, }); @@ -26,6 +41,10 @@ export const supabase = createClient(supabaseUrl, supabaseAnonKey, { // NOTE: With proper session management, this should no longer be needed // Once session is set via supabase.auth.setSession(), the base client will have auth context export const getAuthenticatedClient = (accessToken: string) => { + if (!supabaseUrl || !supabaseAnonKey) { + throw new Error('Missing Supabase environment variables. Please set VITE_SUPABASE_URL and VITE_SUPABASE_ANON_KEY.'); + } + return createClient(supabaseUrl, supabaseAnonKey, { auth: { autoRefreshToken: false,