-
Notifications
You must be signed in to change notification settings - Fork 123
/
supabase.client.ts
47 lines (41 loc) · 1.4 KB
/
supabase.client.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
import { createBrowserClient } from '@supabase/ssr'
import type { Session, SupabaseClient } from '@supabase/supabase-js'
import { fetchWithRetry } from '../utils/fetch-retry'
import type { Plugin } from '#app'
import { defineNuxtPlugin, useRuntimeConfig, useSupabaseSession, useSupabaseUser } from '#imports'
export default defineNuxtPlugin({
name: 'supabase',
enforce: 'pre',
async setup() {
const { url, key, cookieOptions, clientOptions } = useRuntimeConfig().public.supabase
const client = createBrowserClient(url, key, {
...clientOptions,
cookieOptions,
isSingleton: true,
global: {
fetch: fetchWithRetry,
...clientOptions.global,
},
})
const currentSession = useSupabaseSession()
const currentUser = useSupabaseUser()
// Initialize user and session states
const {
data: { session },
} = await client.auth.getSession()
currentSession.value = session
currentUser.value = session?.user ?? null
// Updates the session and user states through auth events
client.auth.onAuthStateChange((_, session: Session | null) => {
if (JSON.stringify(currentSession.value) !== JSON.stringify(session)) {
currentSession.value = session
currentUser.value = session?.user ?? null
}
})
return {
provide: {
supabase: { client },
},
}
},
}) as Plugin<{ client: SupabaseClient }>