-
-
Notifications
You must be signed in to change notification settings - Fork 240
/
serverComponentClient.ts
82 lines (76 loc) · 2.44 KB
/
serverComponentClient.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
72
73
74
75
76
77
78
79
80
81
82
import {
CookieAuthStorageAdapter,
CookieOptions,
CookieOptionsWithName,
SupabaseClientOptionsWithoutAuth,
createSupabaseClient
} from '@supabase/auth-helpers-shared';
import { cookies } from 'next/headers';
import type { SupabaseClient } from '@supabase/supabase-js';
import type { GenericSchema } from '@supabase/supabase-js/dist/module/lib/types';
class NextServerComponentAuthStorageAdapter extends CookieAuthStorageAdapter {
readonly isServer = true;
constructor(
private readonly context: {
cookies: () => ReturnType<typeof cookies>;
},
cookieOptions?: CookieOptions
) {
super(cookieOptions);
}
protected getCookie(name: string): string | null | undefined {
const nextCookies = this.context.cookies();
return nextCookies.get(name)?.value;
}
protected setCookie(name: string, value: string): void {
// Server Components cannot set cookies. Must use Middleware, Server Action or Route Handler
// https://github.com/vercel/next.js/discussions/41745#discussioncomment-5198848
}
protected deleteCookie(name: string): void {
// Server Components cannot set cookies. Must use Middleware, Server Action or Route Handler
// https://github.com/vercel/next.js/discussions/41745#discussioncomment-5198848
}
}
export function createServerComponentClient<
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
>(
context: {
cookies: () => ReturnType<typeof cookies>;
},
{
supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL,
supabaseKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY,
options,
cookieOptions
}: {
supabaseUrl?: string;
supabaseKey?: string;
options?: SupabaseClientOptionsWithoutAuth<SchemaName>;
cookieOptions?: CookieOptionsWithName;
} = {}
): 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!'
);
}
return createSupabaseClient<Database, SchemaName, Schema>(supabaseUrl, supabaseKey, {
...options,
global: {
...options?.global,
headers: {
...options?.global?.headers,
'X-Client-Info': `${PACKAGE_NAME}@${PACKAGE_VERSION}`
}
},
auth: {
storage: new NextServerComponentAuthStorageAdapter(context, cookieOptions)
}
});
}