Skip to content
Closed
Show file tree
Hide file tree
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
19 changes: 19 additions & 0 deletions packages/core/auth-js/src/GoTrueClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4540,6 +4540,17 @@ export default class GoTrueClient {
error
)
await this._removeSession()
} else {
// The refresh failed with a retryable error (e.g. network still
// reconnecting after tab suspension). Emit SIGNED_IN with the
// current session so downstream listeners (realtime, functions)
// can re-sync with the existing token. The auto-refresh ticker
// will retry the actual refresh on its next tick.
this._debug(
debugName,
'refresh failed with a retryable error, notifying subscribers with current session'
)
await this._notifyAllSubscribers('SIGNED_IN', currentSession)
}
}
}
Expand Down Expand Up @@ -5029,6 +5040,14 @@ export default class GoTrueClient {
// recover the session
await this._recoverAndRefresh()
})

// After lock-based recovery, if the session is still expired
// (e.g. network was not yet available when _recoverAndRefresh ran),
// trigger an immediate auto-refresh tick so we don't wait up to
// AUTO_REFRESH_TICK_DURATION_MS (30s) for the next scheduled tick.
if (this.autoRefreshToken) {
await this._autoRefreshTokenTick()
}
}
} else if (document.visibilityState === 'hidden') {
if (this.autoRefreshToken) {
Expand Down
28 changes: 28 additions & 0 deletions packages/core/supabase-js/src/SupabaseClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -355,6 +355,7 @@ export default class SupabaseClient<

if (!settings.accessToken) {
this._listenForAuthEvents()
this._listenForVisibilityChange()
}
}

Expand Down Expand Up @@ -596,6 +597,33 @@ export default class SupabaseClient<
return data
}

/**
* Listens for browser visibility changes (tab resume after suspension).
* When the tab becomes visible again, force-syncs a fresh token to
* the realtime client. This handles the case where a token refresh
* during _recoverAndRefresh fails (e.g. network still reconnecting)
* and no TOKEN_REFRESHED event fires, leaving realtime with a stale token.
*/
private _listenForVisibilityChange() {
if (typeof globalThis === 'undefined' || typeof document === 'undefined') {
return
}

const callback = async () => {
if (document.visibilityState === 'visible') {
// Tab just became visible — push fresh token to realtime.
// _getAccessToken reads from auth.getSession which will trigger
// a refresh if the session has expired.
const token = await this._getAccessToken()
if (token && token !== this.supabaseKey) {
this.realtime.setAuth(token)
}
}
}

document.addEventListener('visibilitychange', callback)
}

private _handleTokenChanged(
event: AuthChangeEvent,
source: 'CLIENT' | 'STORAGE',
Expand Down
37 changes: 37 additions & 0 deletions packages/core/supabase-js/test/unit/SupabaseClient.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -378,6 +378,43 @@ describe('SupabaseClient', () => {
expect(client.realtime.setAuth).toHaveBeenCalledWith(testToken)
expect((client.realtime as any).accessTokenValue).toBe(testToken)
})

test('should sync fresh token to realtime on visibility change (tab resume)', async () => {
// Set up a minimal document mock for the visibility change listener
const listeners: Record<string, Function[]> = {}
const mockDocument = {
visibilityState: 'visible',
addEventListener: (event: string, cb: Function) => {
listeners[event] = listeners[event] || []
listeners[event].push(cb)
},
dispatchEvent: (event: { type: string }) => {
;(listeners[event.type] || []).forEach((cb) => cb())
},
}
;(globalThis as any).document = mockDocument

const freshToken = 'fresh-session-token'
const client = createClient(URL, KEY)

client.auth.getSession = jest.fn().mockResolvedValue({
data: { session: { access_token: freshToken } },
})

const setAuthSpy = jest.spyOn(client.realtime, 'setAuth').mockResolvedValue()

// Simulate tab becoming visible (as after suspension)
mockDocument.visibilityState = 'visible'
mockDocument.dispatchEvent({ type: 'visibilitychange' })

// Allow async callback to complete
await new Promise((r) => setTimeout(r, 50))

expect(setAuthSpy).toHaveBeenCalledWith(freshToken)

// Clean up
delete (globalThis as any).document
})
})

describe('FetchWithAuth Token Integration', () => {
Expand Down