Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(ceremony): refresh session #3140

Merged
merged 1 commit into from
Oct 24, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 66 additions & 4 deletions ceremony/src/lib/supabase/client.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,72 @@
import { createClient, type SupabaseClient } from "@supabase/supabase-js"
import { browser } from "$app/environment"

const SUPABASE_ANON_KEY = import.meta.env.VITE_SUPABASE_ANON_KEY
const SUPABASE_URL = import.meta.env.VITE_SUPABASE_URL

export const supabase: SupabaseClient = createClient(SUPABASE_URL, SUPABASE_ANON_KEY, {
auth: {
autoRefreshToken: true
export const createSupabaseClient = () => {
let client: SupabaseClient | null = null
let refreshInterval: NodeJS.Timeout | null = null
const REFRESH_INTERVAL = 5 * 60 * 1000 // 5 minutes

const getClient = () => {
if (client) return client

client = createClient(SUPABASE_URL, SUPABASE_ANON_KEY)

if (browser) {
const refreshSession = async (supabase: SupabaseClient) => {
try {
const {
data: { session },
error
} = await supabase.auth.getSession()

if (error || !session) {
if (refreshInterval) clearInterval(refreshInterval)
refreshInterval = null
return
}

const {
data: { session: newSession },
error: refreshError
} = await supabase.auth.refreshSession({
refresh_token: session.refresh_token
})

if (refreshError) {
console.error("Session refresh failed:", refreshError)
return
}

if (!newSession) {
if (refreshInterval) clearInterval(refreshInterval)
refreshInterval = null
}
} catch (error) {
console.error("Session refresh failed:", error)
}
}

refreshInterval = setInterval(() => {
if (client) {
refreshSession(client)
}
}, REFRESH_INTERVAL)

// Clean up on window unload
window.addEventListener("beforeunload", () => {
if (refreshInterval) {
clearInterval(refreshInterval)
}
})
}

return client
}
})

return getClient()
}

export const supabase = createSupabaseClient()