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

supabase / supabase-js / 15158416212

21 May 2025 09:19AM UTC coverage: 72.523% (-0.1%) from 72.646%
15158416212

Pull #1425

github

web-flow
Merge 4eb0c34aa into f25477396
Pull Request #1425: fix: preserve path segments in supabaseUrl when constructing endpoints.

53 of 91 branches covered (58.24%)

Branch coverage included in aggregate %.

7 of 7 new or added lines in 2 files covered. (100.0%)

6 existing lines in 1 file now uncovered.

108 of 131 relevant lines covered (82.44%)

8.57 hits per line

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

73.83
/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: 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 baseUrl = new URL(supabaseUrl)
19✔
79

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

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

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

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

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

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

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

132
    if (!settings.accessToken) {
19✔
133
      this._listenForAuthEvents()
18✔
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.href, {
1✔
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.href, this.headers, this.fetch)
1✔
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> {
UNCOV
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)
1✔
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: {
2✔
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
    FnName,
230
    null
231
  > {
232
    return this.rest.rpc(fn, args, options)
3✔
233
  }
234

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

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

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

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

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

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

UNCOV
277
    return data.session?.access_token ?? null
×
278
  }
279

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

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

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

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

© 2026 Coveralls, Inc