Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

feat: add centralized, cached access to the access token

Stojan Dimitrovskic0f602617b83
diff --git a/studio/data/fetchers.ts b/studio/data/fetchers.ts
index 61eff3ac84e..6c5ca18facd 100644
--- a/studio/data/fetchers.ts
+++ b/studio/data/fetchers.ts
@@ -1,5 +1,5 @@
import { API_URL } from 'lib/constants'
-import { auth } from 'lib/gotrue'
+import { getAccessToken } from 'lib/gotrue'
import { uuidv4 } from 'lib/helpers'
import createClient from 'openapi-fetch'
import { paths } from './api' // generated from openapi-typescript
@@ -27,17 +27,6 @@ const {
headers: DEFAULT_HEADERS,
})
-export async function getAccessToken() {
- // ignore if server-side
- if (typeof window === 'undefined') return undefined
-
- const {
- data: { session },
- } = await auth.getSession()
-
- return session?.access_token
-}
-
export async function constructHeaders(headersInit?: HeadersInit | undefined) {
const requestId = uuidv4()
const headers = new Headers(headersInit)
diff --git a/studio/lib/common/fetch/base.ts b/studio/lib/common/fetch/base.ts
index 1e338f28ca1..42c4d1fc8be 100644
--- a/studio/lib/common/fetch/base.ts
+++ b/studio/lib/common/fetch/base.ts
@@ -1,4 +1,4 @@
-import { auth } from 'lib/gotrue'
+import { getAccessToken } from 'lib/gotrue'
import { isUndefined } from 'lodash'
import { SupaResponse } from 'types/base'
import { Session } from '@supabase/gotrue-js'
@@ -87,34 +87,6 @@ export async function handleResponseError<T = unknown>(
}
}
-let currentSession: Session | null = null
-
-auth.onAuthStateChange((event, session) => {
- currentSession = session
-})
-
-export async function getAccessToken() {
- // ignore if server-side
- if (typeof window === 'undefined') return ''
-
- const aboutToExpire = currentSession?.expires_at
- ? currentSession.expires_at - Math.ceil(Date.now() / 1000) < 60
- : false
-
- if (!currentSession || aboutToExpire) {
- const {
- data: { session },
- } = await auth.getSession()
-
- currentSession = session
- }
-
- // using memory version as gotrue-js can be a bit slow when using
- // #getSession() as it has to read directly from local storage
-
- return currentSession?.access_token
-}
-
export async function constructHeaders(requestId: string, optionHeaders?: { [prop: string]: any }) {
let headers: { [prop: string]: any } = {
'Content-Type': 'application/json',
diff --git a/studio/lib/gotrue.ts b/studio/lib/gotrue.ts
index c132a36ab51..c89d359bf2f 100644
--- a/studio/lib/gotrue.ts
+++ b/studio/lib/gotrue.ts
@@ -1,5 +1,5 @@
import { IS_PLATFORM } from './constants'
-import { User } from '@supabase/gotrue-js'
+import { User, Session } from '@supabase/gotrue-js'
import { gotrueClient } from 'common'
import { getFlags } from './configcat'
import { getNavigatorLockFeatureFlagThreshold, setNavigatorLockEnabled } from './local-storage'
@@ -37,6 +37,53 @@ export { STORAGE_KEY } from 'common'
export const auth = gotrueClient
+let currentSession: Session | null = null
+let getAccessTokenPromise: Promise<string | undefined | null> | null = null
+
+auth.onAuthStateChange((event, session) => {
+ currentSession = session
+})
+
+/**
+ * Grabs the currently available access token, or starts a single getSession call.
+ */
+export async function getAccessToken() {
+ // ignore if server-side
+ if (typeof window === 'undefined') return undefined
+
+ const aboutToExpire = currentSession?.expires_at
+ ? currentSession.expires_at - Math.ceil(Date.now() / 1000) < 30
+ : false
+
+ if (!currentSession || aboutToExpire) {
+ if (!getAccessTokenPromise) {
+ const promise = (async () => {
+ try {
+ const {
+ data: { session },
+ error,
+ } = await auth.getSession()
+ if (error) {
+ throw error
+ }
+
+ return session?.access_token
+ } finally {
+ getAccessTokenPromise = null
+ }
+ })()
+
+ getAccessTokenPromise = promise
+
+ return await promise
+ }
+
+ return await getAccessTokenPromise
+ }
+
+ return currentSession.access_token
+}
+
export const getAuthUser = async (token: String): Promise<any> => {
try {
const {