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

supabase / supabase-js / 15874278845

25 Jun 2025 10:46AM UTC coverage: 72.889%. Remained the same
15874278845

Pull #1468

github

web-flow
Merge e03bdb03f into 008063e4e
Pull Request #1468: fix: bump realtime-js to 2.11.15

55 of 93 branches covered (59.14%)

Branch coverage included in aggregate %.

109 of 132 relevant lines covered (82.58%)

8.81 hits per line

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

74.07
/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 { ensureTrailingSlash, 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: URL
47
  protected authUrl: URL
48
  protected storageUrl: URL
49
  protected functionsUrl: URL
50
  protected rest: PostgrestClient<Database, SchemaName, Schema>
51
  protected storageKey: string
52
  protected fetch?: Fetch
53
  protected changedAccessToken?: string
54
  protected accessToken?: () => Promise<string | null>
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,
21✔
72
    protected supabaseKey: string,
21✔
73
    options?: SupabaseClientOptions<SchemaName>
74
  ) {
75
    if (!supabaseUrl) throw new Error('supabaseUrl is required.')
21✔
76
    if (!supabaseKey) throw new Error('supabaseKey is required.')
20✔
77

78
    const _supabaseUrl = ensureTrailingSlash(supabaseUrl)
19✔
79
    const baseUrl = new URL(_supabaseUrl)
19✔
80

81
    this.realtimeUrl = new URL('realtime/v1', baseUrl)
19✔
82
    this.realtimeUrl.protocol = this.realtimeUrl.protocol.replace('http', 'ws')
19✔
83
    this.authUrl = new URL('auth/v1', baseUrl)
19✔
84
    this.storageUrl = new URL('storage/v1', baseUrl)
19✔
85
    this.functionsUrl = new URL('functions/v1', baseUrl)
19✔
86

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

96
    const settings = applySettingDefaults(options ?? {}, DEFAULTS)
19✔
97

98
    this.storageKey = settings.auth.storageKey ?? ''
19!
99
    this.headers = settings.global.headers ?? {}
19!
100

101
    if (!settings.accessToken) {
19✔
102
      this.auth = this._initSupabaseAuthClient(
18✔
103
        settings.auth ?? {},
54!
104
        this.headers,
105
        settings.global.fetch
106
      )
107
    } else {
108
      this.accessToken = settings.accessToken
1✔
109

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

121
    this.fetch = fetchWithAuth(supabaseKey, this._getAccessToken.bind(this), settings.global.fetch)
19✔
122
    this.realtime = this._initRealtimeClient({
19✔
123
      headers: this.headers,
124
      accessToken: this._getAccessToken.bind(this),
125
      ...settings.realtime,
126
    })
127
    this.rest = new PostgrestClient(new URL('rest/v1', baseUrl).href, {
19✔
128
      headers: this.headers,
129
      schema: settings.db.schema,
130
      fetch: this.fetch,
131
    })
132

133
    if (!settings.accessToken) {
19✔
134
      this._listenForAuthEvents()
18✔
135
    }
136
  }
137

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

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

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

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

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

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

247
  /**
248
   * Returns all Realtime channels.
249
   */
250
  getChannels(): RealtimeChannel[] {
251
    return this.realtime.getChannels()
3✔
252
  }
253

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

264
  /**
265
   * Unsubscribes and removes all Realtime channels from Realtime client.
266
   */
267
  removeAllChannels(): Promise<('ok' | 'timed out' | 'error')[]> {
268
    return this.realtime.removeAllChannels()
1✔
269
  }
270

271
  private async _getAccessToken() {
272
    if (this.accessToken) {
×
273
      return await this.accessToken()
×
274
    }
275

276
    const { data } = await this.auth.getSession()
×
277

278
    return data.session?.access_token ?? null
×
279
  }
280

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

317
  private _initRealtimeClient(options: RealtimeClientOptions) {
318
    return new RealtimeClient(this.realtimeUrl.href, {
19✔
319
      ...options,
320
      params: { ...{ apikey: this.supabaseKey }, ...options?.params },
57!
321
    })
322
  }
323

324
  private _listenForAuthEvents() {
325
    let data = this.auth.onAuthStateChange((event, session) => {
18✔
326
      this._handleTokenChanged(event, 'CLIENT', session?.access_token)
18!
327
    })
328
    return data
18✔
329
  }
330

331
  private _handleTokenChanged(
332
    event: AuthChangeEvent,
333
    source: 'CLIENT' | 'STORAGE',
334
    token?: string
335
  ) {
336
    if (
18!
337
      (event === 'TOKEN_REFRESHED' || event === 'SIGNED_IN') &&
36!
338
      this.changedAccessToken !== token
339
    ) {
340
      this.changedAccessToken = token
×
341
    } else if (event === 'SIGNED_OUT') {
18!
342
      this.realtime.setAuth()
×
343
      if (source == 'STORAGE') this.auth.signOut()
×
344
      this.changedAccessToken = undefined
×
345
    }
346
  }
347
}
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