-
Notifications
You must be signed in to change notification settings - Fork 230
/
Copy pathclientComponentClient.ts
71 lines (65 loc) · 2.33 KB
/
clientComponentClient.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import {
BrowserCookieAuthStorageAdapter,
CookieOptionsWithName,
SupabaseClientOptionsWithoutAuth,
createSupabaseClient
} from '@supabase/auth-helpers-shared';
import type { SupabaseClient } from '@supabase/supabase-js';
import type { GenericSchema } from '@supabase/supabase-js/dist/module/lib/types';
// can't type this properly as `Database`, `SchemaName` and `Schema` are only available within `createClientComponentClient` function
let supabase: any;
export function createClientComponentClient<
Database = any,
SchemaName extends string & keyof Database = 'public' extends keyof Database
? 'public'
: string & keyof Database,
Schema extends GenericSchema = Database[SchemaName] extends GenericSchema
? Database[SchemaName]
: any
>({
supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL,
supabaseKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY,
options,
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 createNewClient = () =>
createSupabaseClient<Database, SchemaName, Schema>(supabaseUrl, supabaseKey, {
...options,
global: {
...options?.global,
headers: {
...options?.global?.headers,
'X-Client-Info': `${PACKAGE_NAME}@${PACKAGE_VERSION}`
}
},
auth: {
storage: new BrowserCookieAuthStorageAdapter(cookieOptions)
}
});
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;
}
// 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();
}