Files
nuzlocke-tracker/frontend/src/lib/supabase.ts
Julian Tabel 22dd569b75 fix: proactively refresh Supabase JWT before API calls
Adds token expiry checking and automatic refresh to prevent intermittent
401 errors when the cached session token expires between interactions.

- Check token expiry (60s buffer) before each API call
- Add 401 interceptor that retries once with refreshed token
- Explicitly enable autoRefreshToken in Supabase client

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-22 10:01:38 +01:00

35 lines
1.2 KiB
TypeScript

import { createClient, type SupabaseClient } from '@supabase/supabase-js'
const supabaseUrl = import.meta.env['VITE_SUPABASE_URL'] ?? ''
const supabaseAnonKey = import.meta.env['VITE_SUPABASE_ANON_KEY'] ?? ''
const isLocalDev = supabaseUrl.includes('localhost')
// supabase-js hardcodes /auth/v1 as the auth path prefix, but GoTrue
// serves at the root when accessed directly (no API gateway).
// This custom fetch strips the prefix for local dev.
function localGoTrueFetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
const url = input instanceof Request ? input.url : String(input)
const rewritten = url.replace('/auth/v1/', '/')
if (input instanceof Request) {
return fetch(new Request(rewritten, input), init)
}
return fetch(rewritten, init)
}
function createSupabaseClient(): SupabaseClient {
if (!supabaseUrl || !supabaseAnonKey) {
return createClient('http://localhost:9999', 'stub-key')
}
return createClient(supabaseUrl, supabaseAnonKey, {
auth: {
autoRefreshToken: true,
persistSession: true,
},
...(isLocalDev && {
global: { fetch: localGoTrueFetch },
}),
})
}
export const supabase = createSupabaseClient()