diff --git a/.changeset/unlucky-planes-think.md b/.changeset/unlucky-planes-think.md new file mode 100644 index 00000000..cfa35bc7 --- /dev/null +++ b/.changeset/unlucky-planes-think.md @@ -0,0 +1,5 @@ +--- +'@supabase/auth-helpers-nextjs': patch +--- + +Allow user to opt out of singleton pattern for Client Components diff --git a/packages/nextjs/src/clientComponentClient.ts b/packages/nextjs/src/clientComponentClient.ts index 5655311d..4f89dc06 100644 --- a/packages/nextjs/src/clientComponentClient.ts +++ b/packages/nextjs/src/clientComponentClient.ts @@ -23,12 +23,14 @@ export function createClientComponentClient< supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL, supabaseKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY, options, - cookieOptions + cookieOptions, + isSingleton = true }: { supabaseUrl?: string; supabaseKey?: string; options?: SupabaseClientOptionsWithoutAuth; cookieOptions?: CookieOptionsWithName; + isSingleton?: boolean; } = {}): SupabaseClient { if (!supabaseUrl || !supabaseKey) { throw new Error( @@ -36,8 +38,7 @@ export function createClientComponentClient< ); } - const _supabase = - supabase ?? + const createNewClient = () => createSupabaseClient(supabaseUrl, supabaseKey, { ...options, global: { @@ -53,10 +54,19 @@ export function createClientComponentClient< } }); - // For SSG and SSR always create a new Supabase client - if (typeof window === 'undefined') return _supabase; - // Create the Supabase client once in the client - if (!supabase) supabase = _supabase; + if (isSingleton) { + // The `Singleton` pattern is the default to simplify the instantiation + // of a Supabase client across Client Components. + const _supabase = supabase ?? createNewClient(); + // For SSG and SSR always create a new Supabase client + if (typeof window === 'undefined') return _supabase; + // Create the Supabase client once in the client + if (!supabase) supabase = _supabase; + return supabase; + } - return supabase; + // This allows for multiple Supabase clients, which may be required when using + // multiple schemas. The user will be responsible for ensuring a single + // instance of Supabase is used across Client Components, for each schema. + return createNewClient(); }