Skip to content

Commit

Permalink
Chore: Extend config options to allow for multiple Supabase clients (#…
Browse files Browse the repository at this point in the history
…571)

* extend config options to allow for unique clients to be created from `createClientComponentClient` function

* add changeset
  • Loading branch information
dijonmusters authored May 31, 2023
1 parent 6e349e2 commit b20cc32
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 8 deletions.
5 changes: 5 additions & 0 deletions .changeset/unlucky-planes-think.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@supabase/auth-helpers-nextjs': patch
---

Allow user to opt out of singleton pattern for Client Components
26 changes: 18 additions & 8 deletions packages/nextjs/src/clientComponentClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,21 +23,22 @@ 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<SchemaName>;
cookieOptions?: CookieOptionsWithName;
isSingleton?: boolean;
} = {}): SupabaseClient<Database, SchemaName, Schema> {
if (!supabaseUrl || !supabaseKey) {
throw new Error(
'either NEXT_PUBLIC_SUPABASE_URL and NEXT_PUBLIC_SUPABASE_ANON_KEY env variables or supabaseUrl and supabaseKey are required!'
);
}

const _supabase =
supabase ??
const createNewClient = () =>
createSupabaseClient<Database, SchemaName, Schema>(supabaseUrl, supabaseKey, {
...options,
global: {
Expand All @@ -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();
}

0 comments on commit b20cc32

Please sign in to comment.