Skip to content

Commit 02045f0

Browse files
committed
fix: setAuth ran automatically for realtime; prioritize setAuth tasks
1 parent e6bc2ae commit 02045f0

File tree

2 files changed

+336
-107
lines changed

2 files changed

+336
-107
lines changed

src/SupabaseClient.ts

Lines changed: 20 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,7 @@ export default class SupabaseClient<
131131
})
132132

133133
if (!settings.accessToken) {
134-
this._listenForAuthEvents()
134+
setTimeout(() => this._listenForAuthEvents(), 0)
135135
}
136136
}
137137

@@ -268,7 +268,7 @@ export default class SupabaseClient<
268268
return this.realtime.removeAllChannels()
269269
}
270270

271-
private async _getAccessToken() {
271+
protected async _getAccessToken() {
272272
if (this.accessToken) {
273273
return await this.accessToken()
274274
}
@@ -278,7 +278,7 @@ export default class SupabaseClient<
278278
return data.session?.access_token ?? null
279279
}
280280

281-
private _initSupabaseAuthClient(
281+
protected _initSupabaseAuthClient(
282282
{
283283
autoRefreshToken,
284284
persistSession,
@@ -314,21 +314,23 @@ export default class SupabaseClient<
314314
})
315315
}
316316

317-
private _initRealtimeClient(options: RealtimeClientOptions) {
317+
protected _initRealtimeClient(options: RealtimeClientOptions) {
318318
return new RealtimeClient(this.realtimeUrl.href, {
319319
...options,
320320
params: { ...{ apikey: this.supabaseKey }, ...options?.params },
321321
})
322322
}
323323

324-
private _listenForAuthEvents() {
325-
let data = this.auth.onAuthStateChange((event, session) => {
326-
this._handleTokenChanged(event, 'CLIENT', session?.access_token)
324+
protected async _listenForAuthEvents() {
325+
return await this.auth.onAuthStateChange((event, session) => {
326+
setTimeout(
327+
async () => await this._handleTokenChanged(event, 'CLIENT', session?.access_token),
328+
0
329+
)
327330
})
328-
return data
329331
}
330332

331-
private _handleTokenChanged(
333+
protected async _handleTokenChanged(
332334
event: AuthChangeEvent,
333335
source: 'CLIENT' | 'STORAGE',
334336
token?: string
@@ -338,10 +340,16 @@ export default class SupabaseClient<
338340
this.changedAccessToken !== token
339341
) {
340342
this.changedAccessToken = token
343+
this.realtime.setAuth(token)
341344
} else if (event === 'SIGNED_OUT') {
342-
this.realtime.setAuth()
343-
if (source == 'STORAGE') this.auth.signOut()
344-
this.changedAccessToken = undefined
345+
try {
346+
await this.realtime.setAuth()
347+
if (source == 'STORAGE') this.auth.signOut()
348+
} catch (error) {
349+
console.log('Failed to set auth for realtime client:', error)
350+
} finally {
351+
this.changedAccessToken = undefined
352+
}
345353
}
346354
}
347355
}

0 commit comments

Comments
 (0)