• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

supabase / supabase-js / 12179605440

05 Dec 2024 12:19PM UTC coverage: 67.633% (+1.6%) from 66.038%
12179605440

Pull #1320

github

web-flow
Merge 4335cb20b into 456f27e02
Pull Request #1320: feat: Realtime using accessToken callback for auth

41 of 79 branches covered (51.9%)

Branch coverage included in aggregate %.

1 of 1 new or added line in 1 file covered. (100.0%)

1 existing line in 1 file now uncovered.

99 of 128 relevant lines covered (77.34%)

4.63 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

67.27
/src/SupabaseClient.ts
1
import { FunctionsClient } from '@supabase/functions-js'
2✔
2
import { AuthChangeEvent } from '@supabase/auth-js'
3
import {
2✔
4
  PostgrestClient,
5
  PostgrestFilterBuilder,
6
  PostgrestQueryBuilder,
7
} from '@supabase/postgrest-js'
8
import {
2✔
9
  RealtimeChannel,
10
  RealtimeChannelOptions,
11
  RealtimeClient,
12
  RealtimeClientOptions,
13
} from '@supabase/realtime-js'
14
import { StorageClient as SupabaseStorageClient } from '@supabase/storage-js'
2✔
15
import {
2✔
16
  DEFAULT_GLOBAL_OPTIONS,
17
  DEFAULT_DB_OPTIONS,
18
  DEFAULT_AUTH_OPTIONS,
19
  DEFAULT_REALTIME_OPTIONS,
20
} from './lib/constants'
21
import { fetchWithAuth } from './lib/fetch'
2✔
22
import { stripTrailingSlash, applySettingDefaults } from './lib/helpers'
2✔
23
import { SupabaseAuthClient } from './lib/SupabaseAuthClient'
2✔
24
import { Fetch, GenericSchema, SupabaseClientOptions, SupabaseAuthClientOptions } from './lib/types'
25

26
/**
27
 * Supabase Client.
28
 *
29
 * An isomorphic Javascript client for interacting with Postgres.
30
 */
31
export default class SupabaseClient<
2✔
32
  Database = any,
33
  SchemaName extends string & keyof Database = 'public' extends keyof Database
34
    ? 'public'
35
    : string & keyof Database,
36
  Schema extends GenericSchema = Database[SchemaName] extends GenericSchema
37
    ? Database[SchemaName]
38
    : any
39
> {
40
  /**
41
   * Supabase Auth allows you to create and manage user sessions for access to data that is secured by access policies.
42
   */
43
  auth: SupabaseAuthClient
44
  realtime: RealtimeClient
45

46
  protected realtimeUrl: string
47
  protected authUrl: string
48
  protected storageUrl: string
49
  protected functionsUrl: string
50
  protected rest: PostgrestClient<Database, SchemaName>
51
  protected storageKey: string
52
  protected fetch?: Fetch
53
  protected changedAccessToken?: string
54
  protected accessToken?: () => Promise<string>
55

56
  protected headers: Record<string, string>
57

58
  /**
59
   * Create a new client for use in the browser.
60
   * @param supabaseUrl The unique Supabase URL which is supplied when you create a new project in your project dashboard.
61
   * @param supabaseKey The unique Supabase Key which is supplied when you create a new project in your project dashboard.
62
   * @param options.db.schema You can switch in between schemas. The schema needs to be on the list of exposed schemas inside Supabase.
63
   * @param options.auth.autoRefreshToken Set to "true" if you want to automatically refresh the token before expiring.
64
   * @param options.auth.persistSession Set to "true" if you want to automatically save the user session into local storage.
65
   * @param options.auth.detectSessionInUrl Set to "true" if you want to automatically detects OAuth grants in the URL and signs in the user.
66
   * @param options.realtime Options passed along to realtime-js constructor.
67
   * @param options.global.fetch A custom fetch implementation.
68
   * @param options.global.headers Any additional headers to send with each network request.
69
   */
70
  constructor(
71
    protected supabaseUrl: string,
10✔
72
    protected supabaseKey: string,
10✔
73
    options?: SupabaseClientOptions<SchemaName>
74
  ) {
75
    if (!supabaseUrl) throw new Error('supabaseUrl is required.')
10✔
76
    if (!supabaseKey) throw new Error('supabaseKey is required.')
9✔
77

78
    const _supabaseUrl = stripTrailingSlash(supabaseUrl)
8✔
79

80
    this.realtimeUrl = `${_supabaseUrl}/realtime/v1`.replace(/^http/i, 'ws')
8✔
81
    this.authUrl = `${_supabaseUrl}/auth/v1`
8✔
82
    this.storageUrl = `${_supabaseUrl}/storage/v1`
8✔
83
    this.functionsUrl = `${_supabaseUrl}/functions/v1`
8✔
84

85
    // default storage key uses the supabase project ref as a namespace
86
    const defaultStorageKey = `sb-${new URL(this.authUrl).hostname.split('.')[0]}-auth-token`
8✔
87
    const DEFAULTS = {
8✔
88
      db: DEFAULT_DB_OPTIONS,
89
      realtime: DEFAULT_REALTIME_OPTIONS,
90
      auth: { ...DEFAULT_AUTH_OPTIONS, storageKey: defaultStorageKey },
91
      global: DEFAULT_GLOBAL_OPTIONS,
92
    }
93

94
    const settings = applySettingDefaults(options ?? {}, DEFAULTS)
8✔
95

96
    this.storageKey = settings.auth.storageKey ?? ''
8!
97
    this.headers = settings.global.headers ?? {}
8!
98

99
    if (!settings.accessToken) {
8✔
100
      this.auth = this._initSupabaseAuthClient(
7✔
101
        settings.auth ?? {},
21!
102
        this.headers,
103
        settings.global.fetch
104
      )
105
    } else {
106
      this.accessToken = settings.accessToken
1✔
107

108
      this.auth = new Proxy<SupabaseAuthClient>({} as any, {
1✔
109
        get: (_, prop) => {
110
          throw new Error(
1✔
111
            `@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(
112
              prop
113
            )} is not possible`
114
          )
115
        },
116
      })
117
    }
118

119
    this.fetch = fetchWithAuth(supabaseKey, this._getAccessToken.bind(this), settings.global.fetch)
8✔
120

121
    this.realtime = this._initRealtimeClient({
8✔
122
      headers: this.headers,
123
      accessToken: this._getAccessToken,
124
      ...settings.realtime,
125
    })
126
    this.rest = new PostgrestClient(`${_supabaseUrl}/rest/v1`, {
8✔
127
      headers: this.headers,
128
      schema: settings.db.schema,
129
      fetch: this.fetch,
130
    })
131

132
    if (!settings.accessToken) {
8✔
133
      this._listenForAuthEvents()
7✔
134
    }
135
  }
136

137
  /**
138
   * Supabase Functions allows you to deploy and invoke edge functions.
139
   */
140
  get functions(): FunctionsClient {
141
    return new FunctionsClient(this.functionsUrl, {
×
142
      headers: this.headers,
143
      customFetch: this.fetch,
144
    })
145
  }
146

147
  /**
148
   * Supabase Storage allows you to manage user-generated content, such as photos or videos.
149
   */
150
  get storage(): SupabaseStorageClient {
151
    return new SupabaseStorageClient(this.storageUrl, this.headers, this.fetch)
×
152
  }
153

154
  // NOTE: signatures must be kept in sync with PostgrestClient.from
155
  from<
156
    TableName extends string & keyof Schema['Tables'],
157
    Table extends Schema['Tables'][TableName]
158
  >(relation: TableName): PostgrestQueryBuilder<Schema, Table, TableName>
159
  from<ViewName extends string & keyof Schema['Views'], View extends Schema['Views'][ViewName]>(
160
    relation: ViewName
161
  ): PostgrestQueryBuilder<Schema, View, ViewName>
162
  /**
163
   * Perform a query on a table or a view.
164
   *
165
   * @param relation - The table or view name to query
166
   */
167
  from(relation: string): PostgrestQueryBuilder<Schema, any, any> {
168
    return this.rest.from(relation)
×
169
  }
170

171
  // NOTE: signatures must be kept in sync with PostgrestClient.schema
172
  /**
173
   * Select a schema to query or perform an function (rpc) call.
174
   *
175
   * The schema needs to be on the list of exposed schemas inside Supabase.
176
   *
177
   * @param schema - The schema to query
178
   */
179
  schema<DynamicSchema extends string & keyof Database>(
180
    schema: DynamicSchema
181
  ): PostgrestClient<
182
    Database,
183
    DynamicSchema,
184
    Database[DynamicSchema] extends GenericSchema ? Database[DynamicSchema] : any
185
  > {
186
    return this.rest.schema<DynamicSchema>(schema)
2✔
187
  }
188

189
  // NOTE: signatures must be kept in sync with PostgrestClient.rpc
190
  /**
191
   * Perform a function call.
192
   *
193
   * @param fn - The function name to call
194
   * @param args - The arguments to pass to the function call
195
   * @param options - Named parameters
196
   * @param options.head - When set to `true`, `data` will not be returned.
197
   * Useful if you only need the count.
198
   * @param options.get - When set to `true`, the function will be called with
199
   * read-only access mode.
200
   * @param options.count - Count algorithm to use to count rows returned by the
201
   * function. Only applicable for [set-returning
202
   * functions](https://www.postgresql.org/docs/current/functions-srf.html).
203
   *
204
   * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the
205
   * hood.
206
   *
207
   * `"planned"`: Approximated but fast count algorithm. Uses the Postgres
208
   * statistics under the hood.
209
   *
210
   * `"estimated"`: Uses exact count for low numbers and planned count for high
211
   * numbers.
212
   */
213
  rpc<FnName extends string & keyof Schema['Functions'], Fn extends Schema['Functions'][FnName]>(
214
    fn: FnName,
215
    args: Fn['Args'] = {},
1✔
216
    options: {
1✔
217
      head?: boolean
218
      get?: boolean
219
      count?: 'exact' | 'planned' | 'estimated'
220
    } = {}
221
  ): PostgrestFilterBuilder<
222
    Schema,
223
    Fn['Returns'] extends any[]
224
      ? Fn['Returns'][number] extends Record<string, unknown>
225
        ? Fn['Returns'][number]
226
        : never
227
      : never,
228
    Fn['Returns']
229
  > {
230
    return this.rest.rpc(fn, args, options)
1✔
231
  }
232

233
  /**
234
   * Creates a Realtime channel with Broadcast, Presence, and Postgres Changes.
235
   *
236
   * @param {string} name - The name of the Realtime channel.
237
   * @param {Object} opts - The options to pass to the Realtime channel.
238
   *
239
   */
240
  channel(name: string, opts: RealtimeChannelOptions = { config: {} }): RealtimeChannel {
×
241
    return this.realtime.channel(name, opts)
×
242
  }
243

244
  /**
245
   * Returns all Realtime channels.
246
   */
247
  getChannels(): RealtimeChannel[] {
248
    return this.realtime.getChannels()
×
249
  }
250

251
  /**
252
   * Unsubscribes and removes Realtime channel from Realtime client.
253
   *
254
   * @param {RealtimeChannel} channel - The name of the Realtime channel.
255
   *
256
   */
257
  removeChannel(channel: RealtimeChannel): Promise<'ok' | 'timed out' | 'error'> {
258
    return this.realtime.removeChannel(channel)
×
259
  }
260

261
  /**
262
   * Unsubscribes and removes all Realtime channels from Realtime client.
263
   */
264
  removeAllChannels(): Promise<('ok' | 'timed out' | 'error')[]> {
265
    return this.realtime.removeAllChannels()
×
266
  }
267

268
  private async _getAccessToken() {
269
    if (this.accessToken) {
×
270
      return await this.accessToken()
×
271
    }
272

273
    const { data } = await this.auth.getSession()
×
274

275
    return data.session?.access_token ?? null
×
276
  }
277

278
  private _initSupabaseAuthClient(
279
    {
280
      autoRefreshToken,
281
      persistSession,
282
      detectSessionInUrl,
283
      storage,
284
      storageKey,
285
      flowType,
286
      lock,
287
      debug,
288
    }: SupabaseAuthClientOptions,
289
    headers?: Record<string, string>,
290
    fetch?: Fetch
291
  ) {
292
    const authHeaders = {
8✔
293
      Authorization: `Bearer ${this.supabaseKey}`,
294
      apikey: `${this.supabaseKey}`,
295
    }
296
    return new SupabaseAuthClient({
8✔
297
      url: this.authUrl,
298
      headers: { ...authHeaders, ...headers },
299
      storageKey: storageKey,
300
      autoRefreshToken,
301
      persistSession,
302
      detectSessionInUrl,
303
      storage,
304
      flowType,
305
      lock,
306
      debug,
307
      fetch,
308
      // auth checks if there is a custom authorizaiton header using this flag
309
      // so it knows whether to return an error when getUser is called with no session
310
      hasCustomAuthorizationHeader: 'Authorization' in this.headers ?? false,
24!
311
    })
312
  }
313

314
  private _initRealtimeClient(options: RealtimeClientOptions) {
315
    return new RealtimeClient(this.realtimeUrl, {
8✔
316
      ...options,
317
      params: { ...{ apikey: this.supabaseKey }, ...options?.params },
24!
318
    })
319
  }
320

321
  private _listenForAuthEvents() {
322
    let data = this.auth.onAuthStateChange((event, session) => {
7✔
323
      this._handleTokenChanged(event, 'CLIENT', session?.access_token)
7!
324
    })
325
    return data
7✔
326
  }
327

328
  private _handleTokenChanged(
329
    event: AuthChangeEvent,
330
    source: 'CLIENT' | 'STORAGE',
331
    token?: string
332
  ) {
333
    if (
7!
334
      (event === 'TOKEN_REFRESHED' || event === 'SIGNED_IN') &&
14!
335
      this.changedAccessToken !== token
336
    ) {
UNCOV
337
      this.changedAccessToken = token
×
338
    } else if (event === 'SIGNED_OUT') {
7!
339
      // Token is removed
340
      this.realtime.setAuth(this.supabaseKey)
×
341
      if (source == 'STORAGE') this.auth.signOut()
×
342
      this.changedAccessToken = undefined
×
343
    }
344
  }
345
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc