forked from supabase/supabase
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsupabase_js_v1.yml
2825 lines (2707 loc) · 97.1 KB
/
supabase_js_v1.yml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
openref: 0.1
info:
id: reference/supabase-js
title: Supabase Javascript Client
description: |
Supabase JavaScript.
definition: ../../spec/enrichments/tsdoc_v1/combined.json
specUrl: https://github.com/supabase/supabase/edit/master/spec/supabase_js_v1.yml
slugPrefix: '/'
libraries:
- id: 'js'
name: 'JavaScript'
version: '0.0.1'
functions:
- id: initializing
title: 'Initializing'
$ref: '@supabase/supabase-js.index.SupabaseClient.constructor'
examples:
- id: create-client
name: Create Client
code: |
```js
import { createClient } from '@supabase/supabase-js'
// Create a single supabase client for interacting with your database
const supabase = createClient('https://xyzcompany.supabase.co', 'public-anon-key')
```
- id: with-additional-parameters
name: With Additional Parameters
code: |
```js
import { createClient } from '@supabase/supabase-js'
const options = {
schema: 'public',
headers: { 'x-my-custom-header': 'my-app-name' },
autoRefreshToken: true,
persistSession: true,
detectSessionInUrl: true,
}
const supabase = createClient('https://xyzcompany.supabase.co', 'public-anon-key', options)
```
- id: api-schemas
name: API schemas
code: |
```js
import { createClient } from '@supabase/supabase-js'
const options = {
schema: 'public',
headers: { 'x-my-custom-header': 'my-app-name' },
autoRefreshToken: true,
persistSession: true,
detectSessionInUrl: true,
}
const supabase = createClient('https://xyzcompany.supabase.co', 'public-anon-key', options)
```
description: |
By default the API server points to the `public` schema. You can enable other database schemas within the Dashboard.
Go to `Settings > API > Schema` and add the schema which you want to expose to the API. You also need to grant `USAGE` on your new schema with the grants you desire, such as `SELECT, INSERT, UPDATE, DELETE`.
Note: each client connection can only access a single schema, so the code above can access the `other_schema` schema but cannot access the `public` schema.
- id: custom-fetch-implementation
name: Custom Fetch Implementation
code: |
```js
import { createClient } from '@supabase/supabase-js'
const supabase = createClient('https://xyzcompany.supabase.co', 'public-anon-key', {
fetch: fetch.bind(globalThis),
})
```
description: |
`supabase-js` uses the [`cross-fetch`](https://www.npmjs.com/package/cross-fetch) library to make HTTP requests,
but an alternative `fetch` implementation can be provided as an option.
This is most useful in environments where `cross-fetch` is not compatible (for instance Cloudflare Workers).
- id: sign-up
title: 'signUp()'
$ref: '@supabase/gotrue-js.GoTrueClient.signUp'
notes: |
- By default, the user will need to verify their email address before logging in. If you would like to change this, you can disable "Email Confirmations" by going to Authentication -> Settings on [supabase.com/dashboard](https://supabase.com/dashboard)
- If "Email Confirmations" is turned on, a `user` is returned but `session` will be null
- If "Email Confirmations" is turned off, both a `user` and a `session` will be returned
- When the user confirms their email address, they will be redirected to localhost:3000 by default. To change this, you can go to Authentication -> Settings on [supabase.com/dashboard](https://supabase.com/dashboard)
- If signUp() is called for an existing confirmed user:
- If "Enable email confirmations" is enabled on the "Authentication" -> "Settings" page, an obfuscated / fake user object will be returned.
- If "Enable email confirmations" is disabled, an error with a message "User already registered" will be returned.
- To check if a user already exists, refer to getUser().
examples:
- id: sign-up
name: Sign up.
isSpotlight: true
code: |
```js
const { user, session, error } = await supabase.auth.signUp({
email: '[email protected]',
password: 'example-password',
})
```
- id: sign-up-with-additional-user-metadata.
name: Sign up with additional user meta data.
isSpotlight: true
code: |
```js
const { user, session, error } = await supabase.auth.signUp(
{
email: '[email protected]',
password: 'example-password',
},
{
data: {
first_name: 'John',
age: 27,
}
}
)
```
- id: sign-up-with-third-party-provider
name: Sign up with third-party providers.
hideCodeBlock: true
description: |
You can sign up with OAuth providers using the [`signIn()`](/docs/reference/javascript/v1/auth-signin#sign-in-using-third-party-providers) method.
- id: sign-up-with-phone
name: Sign up with Phone.
description: |
Supabase supports Phone Auth. After a user has verified their number, they can use the [`signIn()`](/docs/reference/javascript/v1/auth-signin#sign-in-using-phone) method.
code: |
```js
const { user, session, error } = await supabase.auth.signUp({
phone: '+13334445555',
password: 'some-password',
})
// After receiving an SMS with One Time Password.
let { session, error } = await supabase.auth.verifyOTP({
phone: '+13334445555',
token: '123456',
})
```
- id: sign-in
title: 'signIn()'
$ref: '@supabase/gotrue-js.GoTrueClient.signIn'
notes: |
- A user can sign up either via email or OAuth.
- If you provide `email` without a `password`, the user will be sent a magic link.
- The magic link's destination URL is determined by the SITE_URL config variable. To change this, you can go to Authentication -> Settings on [supabase.com/dashboard](https://supabase.com/dashboard)
- Specifying a `provider` will open the browser to the relevant login page.
examples:
- id: sign-in-with-email-and-password
name: Sign in with email and password
isSpotlight: true
code: |
```js
const { user, session, error } = await supabase.auth.signIn({
email: '[email protected]',
password: 'example-password',
})
```
- id: sign-in-with-magic-link
name: Sign in with magic link.
description: If no password is provided, the user will be sent a "magic link" to their email address, which they can click to open your application with a valid session. By default, a given user can only request a Magic Link once every 60 seconds.
code: |
```js
const { user, session, error } = await supabase.auth.signIn({
email: '[email protected]'
})
```
- id: sign-in-with-third-party-provider
name: Sign in using third-party providers.
description: Supabase supports many different [third-party providers](https://supabase.com/docs/guides/auth#providers).
code: |
```js
const { user, session, error } = await supabase.auth.signIn({
// provider can be 'github', 'google', 'gitlab', and more
provider: 'github'
})
```
- id: sign-in-with-phone-and-password
name: Sign in with phone and password
isSpotlight: false
code: |
```js
const { user, session, error } = await supabase.auth.signIn({
phone: '+13334445555',
password: 'some-password',
})
```
- id: sign-in-using-a-third-party-provider-with-redirect
name: Sign in using a third-party provider with redirect
description: |
Note that the `redirectTo` param is only relevant for OAuth logins, where the login flow is managed by
the Auth server. If you are using email/phone logins you should set up your own redirects (within the email/sms template).
Sometimes you want to control where the user is redirected to after they are logged in. Supabase supports this for
any URL path on your website (the URL must either be on the same domain as your [Site URL](https://supabase.com/dashboard/project/_/auth/url-configuration) or match one of the Redirect URLs).
See [redirect URLs and wildcards](/docs/guides/auth/overview#redirect-urls-and-wildcards) to add additional redirect URLs to your project.
code: |
```js
const { user, session, error } = await supabase.auth.signIn({
provider: 'github'
}, {
redirectTo: 'https://example.com/welcome'
})
```
- id: sign-in-with-scopes
name: Sign in with scopes
description: |
If you need additional data from an OAuth provider, you can include a space-separated list of scopes in your request to get back an OAuth provider token.
You may also need to specify the scopes in the provider's OAuth app settings, depending on the provider.
code: |
```js
const { user, session, error } = await supabase.auth.signIn({
provider: 'github'
}, {
scopes: 'repo gist notifications'
})
const oAuthToken = session.provider_token // use to access provider API
```
- id: sign-in-with-refresh-token
name: Sign in using a refresh token (e.g. in React Native).
description: |
If you are completing a sign up or login in a React Native app you can pass the refresh token obtained from the provider to obtain a session.
code: |
```js
// An example using Expo's `AuthSession`
const redirectUri = AuthSession.makeRedirectUri({ useProxy: false });
const provider = 'google';
AuthSession.startAsync({
authUrl: `https://MYSUPABASEAPP.supabase.co/auth/v1/authorize?provider=${provider}&redirect_to=${redirectUri}`,
returnUrl: redirectUri,
}).then(async (response: any) => {
if (!response) return;
const { user, session, error } = await supabase.auth.signIn({
refreshToken: response.params?.refresh_token,
});
});
```
- id: sign-out
title: 'signOut()'
$ref: '@supabase/gotrue-js.GoTrueClient.signOut'
examples:
- id: sign-out
name: Sign out
isSpotlight: true
code: |
```js
const { error } = await supabase.auth.signOut()
```
- id: session
title: 'session()'
$ref: '@supabase/gotrue-js.GoTrueClient.session'
examples:
- id: get-the-session-data
name: Get the session data
isSpotlight: true
code: |
```js
const session = supabase.auth.session()
```
- id: user
title: 'user()'
$ref: '@supabase/gotrue-js.GoTrueClient.user'
notes: |
This method gets the user object from memory.
examples:
- id:
name: Get the logged in user
isSpotlight: true
code: |
```js
const user = supabase.auth.user()
```
- id: auth-update
title: 'update()'
$ref: '@supabase/gotrue-js.GoTrueClient.update'
notes: |
User email: By Default, email updates sends a confirmation link to both the user's current and new email.
To only send a confirmation link to the user's new email, disable **Secure email change** in your project's [email auth provider settings](https://supabase.com/dashboard/project/_/auth/providers).
User metadata: It's generally better to store user data in a table within your public schema (i.e., `public.users`).
Use the `update()` method if you have data which rarely changes or is specific only to the logged in user.
examples:
- id: update-the-email-for-an-authenticated-user
name: Update the email for an authenticated user
description: Sends a "Confirm Email Change" email to the new email address.
isSpotlight: true
code: |
```js
const { user, error } = await supabase.auth.update({email: '[email protected]'})
```
- id: update-the-password-for-an-authenticated-user
name: Update the password for an authenticated user
isSpotlight: true
code: |
```js
const { user, error } = await supabase.auth.update({password: 'new password'})
```
- id: update-the-users-metadata
name: Update the user's metadata
isSpotlight: true
code: |
```js
const { user, error } = await supabase.auth.update({
data: { hello: 'world' }
})
```
- id: set-auth
title: 'setAuth()'
$ref: '@supabase/gotrue-js.GoTrueClient.setAuth'
examples:
- id: basic-example
name: Basic example.
description: This is most useful on server-side functions where you cannot log the user in, but have access to the user's access token.
isSpotlight: true
code: |
```js
function apiFunction(req, res) {
// Assuming the access token was sent as a header "X-Supabase-Auth"
const { access_token } = req.get('X-Supabase-Auth')
// You can now use it within a Supabase Client
const supabase = createClient("https://xyzcompany.supabase.co", "public-anon-key")
const { user, error } = supabase.auth.setAuth(access_token)
// This client will now send requests as this user
const { data } = await supabase.from('your_table').select()
}
```
- id: with-express
name: With Express.
isSpotlight: true
code: |
```js
/**
* Make a request from the client to your server function
*/
async function makeApiRequest() {
const token = newClient.session()?.access_token
await fetch('https://example.com/withAuth', {
method: 'GET',
withCredentials: true,
credentials: 'include',
headers: {
'Content-Type': 'application/json',
'Authorization': bearer, // Your own auth
'X-Supabase-Auth': token, // Set the Supabase user
}
})
}
/**
* Use the Auth token in your server-side function.
*/
async function apiFunction(req, res) {
const { access_token } = req.get('X-Supabase-Auth')
// You can now use it within a Supabase Client
const supabase = createClient("https://xyzcompany.supabase.co", "public-anon-key")
const { user, error } = supabase.auth.setAuth(access_token)
// This client will now send requests as this user
const { data } = await supabase.from('your_table').select()
}
```
- id: on-auth-state-change
title: 'onAuthStateChange()'
$ref: '@supabase/gotrue-js.GoTrueClient.onAuthStateChange'
examples:
- id: listen-to-auth-changes
name: Listen to auth changes
isSpotlight: true
code: |
```js
supabase.auth.onAuthStateChange((event, session) => {
console.log(event, session)
})
```
- id: listen-to-sign-in
name: Listen to sign in
code: |
```js
supabase.auth.onAuthStateChange((event, session) => {
if (event == 'SIGNED_IN') console.log('SIGNED_IN', session)
})
```
- id: listen-to-sign-out
name: Listen to sign out
code: |
```js
supabase.auth.onAuthStateChange((event, session) => {
if (event == 'SIGNED_OUT') console.log('SIGNED_OUT', session)
})
```
- id: listen-to-token-refresh
name: Listen to token refresh
code: |
```js
supabase.auth.onAuthStateChange((event, session) => {
if (event == 'TOKEN_REFRESHED') console.log('TOKEN_REFRESHED', session)
})
```
- id: listen-to-user-updates
name: Listen to user updates
code: |
```js
supabase.auth.onAuthStateChange((event, session) => {
if (event == 'USER_UPDATED') console.log('USER_UPDATED', session)
})
```
- id: listen-to-user-deleted
name: Listen to user deleted
code: |
```js
supabase.auth.onAuthStateChange((event, session) => {
if (event == 'USER_DELETED') console.log('USER_DELETED', session)
})
```
- id: listen-to-password-recovery-events
name: Listen to password recovery events
code: |
```js
supabase.auth.onAuthStateChange((event, session) => {
if (event == 'PASSWORD_RECOVERY') console.log('PASSWORD_RECOVERY', session)
})
```
- id: get-user
title: 'getUser()'
$ref: '@supabase/gotrue-js.GoTrueApi.getUser'
notes: |
- Fetches the user object from the database instead of local storage.
- Note that user() fetches the user object from local storage which might not be the most updated.
- Requires the user's access_token.
examples:
- id: fetch-the-user-object-using-the-access-token-jwt
name: Fetch the user object using the access_token jwt.
isSpotlight: true
code: |
```js
const { user, error } = await supabase.auth.api.getUser(
'ACCESS_TOKEN_JWT',
)
```
- id: list-users
title: 'listUsers()'
$ref: '@supabase/gotrue-js.GoTrueApi.listUsers'
notes: |
- Requires a `service_role` key.
- This function should be called on a server. Never expose your `service_role` key in the browser.
examples:
- id: get-a-full-list-of-users
name: Get a full list of users.
isSpotlight: true
code: |
```js
const { data: user, error } = await supabase.auth.api.listUsers()
```
- id: create-user
title: 'createUser()'
$ref: '@supabase/gotrue-js.GoTrueApi.createUser'
notes: |
- Requires a `service_role` key.
- This function should be called on a server. Never expose your `service_role` key in the browser.
- If you do not provide the `email_confirm` and `phone_confirm` options to this function, both will default to false.
examples:
- id: create-a-new-user-with-custom-user-metadata
name: Create a new user with custom user metadata
isSpotlight: true
code: |
```js
const { data: user, error } = await supabase.auth.api.createUser({
email: '[email protected]',
password: 'password',
user_metadata: { name: 'Yoda' }
})
```
- id: auto-confirm-the-users-email
name: Auto-confirm email.
isSpotlight: true
code: |
```js
const { data: user, error } = await supabase.auth.api.createUser({
email: '[email protected]',
email_confirm: true
})
```
- id: auto-confirm-the-users-phone-number
name: Auto-confirm phone.
isSpotlight: true
code: |
```js
const { data: user, error } = await supabase.auth.api.createUser({
phone: '1234567890',
phone_confirm: true
})
```
- id: delete-user
title: 'deleteUser()'
$ref: '@supabase/gotrue-js.GoTrueApi.deleteUser'
notes: |
- Requires a `service_role` key.
- This function should be called on a server. Never expose your `service_role` key in the browser.
examples:
- id: removes-a-user
name: Remove a user completely.
isSpotlight: true
code: |
```js
const { data: user, error } = await supabase.auth.api.deleteUser(
'715ed5db-f090-4b8c-a067-640ecee36aa0'
)
```
- id: invite-user-by-email
title: 'inviteUserByEmail()'
$ref: '@supabase/gotrue-js.GoTrueApi.inviteUserByEmail'
notes: |
- Requires a `service_role` key.
- This function should only be called on a server. Never expose your `service_role` key in the browser.
- The `inviteUserByEmail()` method is typically used by administrators to invite users to join the application.
examples:
- id: basic-example
name: Basic example.
isSpotlight: false
code: |
```js
const { data: user, error } = await supabase.auth
.api
.inviteUserByEmail('[email protected]')
```
- id: send-mobile-otp
title: 'sendMobileOTP()'
$ref: '@supabase/gotrue-js.GoTrueApi.sendMobileOTP'
notes: |
- Requires a `service_role` key.
- This function should only be called on a server. Never expose your `service_role` key in the browser.
examples:
- id: basic-example
name: Basic example.
isSpotlight: false
code: |
```js
const { data: user, error } = await supabase.auth
.api
.sendMobileOTP('12345879')
```
- id: reset-password-for-email
title: 'resetPasswordForEmail()'
$ref: '@supabase/gotrue-js.GoTrueApi.resetPasswordForEmail'
notes: |
Sends a password reset request to an email address.
- When the user clicks the reset link in the email they are redirected back to your application.
You can configure the URL that the user is redirected to via the `redirectTo` param.
See [redirect URLs and wildcards](/docs/guides/auth/overview#redirect-urls-and-wildcards) to add additional redirect URLs to your project.
- After the user has been redirected successfully, prompt them for a new password and call `updateUser()`:
```js
const { data, error } = await supabase.auth.update({
password: new_password,
})
```
examples:
- id: reset-password
name: Reset password
isSpotlight: true
code: |
```js
const { data, error } = await supabase.auth.api.resetPasswordForEmail(
email,
{ redirectTo: 'https://example.com/update-password' }
)
```
- id: reset-password-react
name: Reset password (React)
isSpotlight: true
code: |
```js
/**
* Step 1: Send the user an email to get a password reset token.
* This email contains a link which sends the user back to your application.
*/
const { data, error } = await supabase.auth.api.resetPasswordForEmail(
email,
{ redirectTo: 'https://example.com/update-password' }
)
/**
* Step 2: Once the user is redirected back to your application,
* ask the user to reset their password.
*/
useEffect(() => {
supabase.auth.onAuthStateChange(async (event, session) => {
if (event == "PASSWORD_RECOVERY") {
const newPassword = prompt("What would you like your new password to be?");
const { data, error } = await supabase.auth.update({
password: newPassword,
})
if (data) alert("Password updated successfully!")
if (error) alert("There was an error updating your password.")
}
})
}, [])
```
- id: generate-link
title: 'generateLink()'
$ref: '@supabase/gotrue-js.GoTrueApi.generateLink'
notes: |
- Requires a `service_role` key.
- This function should only be called on a server. Never expose your `service_role` key in the browser.
examples:
- id: generate-an-invite-link
name: Generate an invite link
isSpotlight: false
code: |
```js
const { data: user, error } = await supabase.auth.api.generateLink(
'invite',
)
```
- id: update-user-by-id
title: 'updateUserById()'
$ref: '@supabase/gotrue-js.GoTrueApi.updateUserById'
notes: |
- Requires a `service_role` key.
- This function should only be called on a server. Never expose your `service_role` key in the browser.
examples:
- id: updates-a-users-email
name: Updates a user's email.
isSpotlight: true
code: |
```js
const { data: user, error } = await supabase.auth.api.updateUserById(
'6aa5d0d4-2a9f-4483-b6c8-0cf4c6c98ac4',
{ email: '[email protected]' }
)
```
- id: updates-a-users-password
name: Updates a user's password.
isSpotlight: true
code: |
```js
const { data: user, error } = await supabase.auth.api.updateUserById(
'6aa5d0d4-2a9f-4483-b6c8-0cf4c6c98ac4',
{ password: 'new_password' }
)
```
- id: updates-a-users-metadata
name: Updates a user's metadata.
isSpotlight: true
code: |
```js
const { data: user, error } = await supabase.auth.api.updateUserById(
'6aa5d0d4-2a9f-4483-b6c8-0cf4c6c98ac4',
{ user_metadata: { hello: 'world' } }
)
```
- id: updates-a-users-app-metadata
name: Updates a user's app_metadata.
isSpotlight: true
code: |
```js
const { data: user, error } = await supabase.auth.api.updateUserById(
'6aa5d0d4-2a9f-4483-b6c8-0cf4c6c98ac4',
{ app_metadata: { plan: 'trial' } }
)
```
- id: confirms-a-users-email-address
name: Confirms a user's email address.
isSpotlight: true
code: |
```js
const { data: user, error } = await supabase.auth.api.updateUserById(
'6aa5d0d4-2a9f-4483-b6c8-0cf4c6c98ac4',
{ email_confirm: true }
)
```
- id: confirms-a-users-phone-number
name: Confirms a user's phone number.
isSpotlight: true
code: |
```js
const { data: user, error } = await supabase.auth.api.updateUserById(
'6aa5d0d4-2a9f-4483-b6c8-0cf4c6c98ac4',
{ phone_confirm: true }
)
```
- id: invoke
title: 'invoke()'
description: |
Invokes a Supabase Edge Function.
$ref: '@supabase/functions-js.FunctionsClient.invoke'
notes: |
- Requires an Authorization header.
- Invoke params generally match the [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) spec.
examples:
- id: basic-invocation
name: Basic invocation.
isSpotlight: true
code: |
```js
const { data, error } = await supabase.functions.invoke('hello', {
body: JSON.stringify({ foo: 'bar' })
})
```
- name: Specifying response type.
description: |
By default, `invoke()` will parse the response as JSON. You can parse the response in the following formats: `json`, `blob`, `text`, and `arrayBuffer`.
isSpotlight: true
code: |
```js
const { data, error } = await supabase.functions.invoke('hello', {
responseType: 'text',
body: JSON.stringify({ foo: 'bar' })
})
```
- id: passing-custom-headers
name: Passing custom headers.
description: |
You can pass custom headers to your Edge Function. Note: supabase-js automatically passes the `Authorization` header with the signed in user's JWT.
isSpotlight: true
code: |
```js
const { data, error } = await supabase.functions.invoke('hello', {
headers: {
"my-custom-header": 'my-custom-header-value'
},
body: JSON.stringify({ foo: 'bar' })
})
```
- id: select
title: 'Fetch data: select()'
$ref: '@supabase/postgrest-js."lib/PostgrestQueryBuilder".PostgrestQueryBuilder.select'
notes: |
- By default, Supabase projects will return a maximum of 1,000 rows. This setting can be changed in Project API Settings. It's recommended that you keep it low to limit the payload size of accidental or malicious requests. You can use `range()` queries to paginate through your data.
- `select()` can be combined with [Modifiers](/docs/reference/javascript/using-modifiers)
- `select()` can be combined with [Filters](/docs/reference/javascript/using-filters)
- If using the Supabase hosted platform `apikey` is technically a reserved keyword, since the API gateway will pluck it out for authentication. [It should be avoided as a column name](https://github.com/supabase/supabase/issues/5465).
examples:
- id: getting-your-data
name: Getting your data
isSpotlight: true
code: |
```js
const { data, error } = await supabase
.from('cities')
.select()
```
- id: selecting-specific-columns
name: Selecting specific columns
description: You can select specific fields from your tables.
code: |
```js
const { data, error } = await supabase
.from('cities')
.select('name')
```
- id: query-foreign-tables
name: Query foreign tables
description: If your database has foreign key relationships, you can query related tables too.
code: |
```js
const { data, error } = await supabase
.from('countries')
.select(`
name,
cities (
name
)
`)
```
note: |
What about join tables
If you're in a situation where your tables are **NOT** directly related, but instead are joined by a _join table_,
you can still use the `select()` method to query the related data. The PostgREST engine detects the relationship automatically.
For more details, [follow the link](https://postgrest.org/en/latest/api.html#embedding-through-join-tables).
- id: query-the-same-foreign-table-multiple-times
name: Query the same foreign table multiple times
description: |
Sometimes you will need to query the same foreign table twice.
In this case, you can use the name of the joined column to identify
which join you intend to use. For convenience, you can also give an
alias for each column. For example, if we had a shop of products,
and we wanted to get the supplier and the purchaser at the same time
(both in the users) table:
code: |
```js
const { data, error } = await supabase
.from('products')
.select(`
id,
supplier:supplier_id ( name ),
purchaser:purchaser_id ( name )
`)
```
- id: filtering-with-inner-joins
name: Filtering with inner joins
description: |
If you want to filter a table based on a child table's values you can use the `!inner()` function. For example, if you wanted
to select all rows in a `message` table which belong to a user with the `username` "Jane":
code: |
```js
const { data, error } = await supabase
.from('messages')
.select('*, users!inner(*)')
.eq('users.username', 'Jane')
```
- id: querying-with-count-option
name: Querying with count option
description: |
You can get the number of rows by using the count option.
Allowed values for count option are `null`, [exact](https://postgrest.org/en/stable/api.html#exact-count), [planned](https://postgrest.org/en/stable/api.html#planned-count) and [estimated](https://postgrest.org/en/stable/api.html#estimated-count).
code: |
```js
const { data, error, count } = await supabase
.from('cities')
.select('name', { count: 'exact' }) // if you don't want to return any rows, you can use { count: 'exact', head: true }
```
- id: querying-json-data
name: Querying JSON data
description: |
If you have data inside of a JSONB column, you can apply select
and query filters to the data values. Postgres offers a
[number of operators](https://www.postgresql.org/docs/current/functions-json.html)
for querying JSON data. Also see
[PostgREST docs](http://postgrest.org/en/v7.0.0/api.html#json-columns) for more details.
code: |
```js
const { data, error } = await supabase
.from('users')
.select(`
id, name,
address->street
`)
.eq('address->postcode', 90210)
```
- name: Return data as CSV
description: |
By default the data is returned in JSON format, however you can also request for it to be returned as Comma Separated Values.
code: |
```js
const { data, error } = await supabase
.from('users')
.select()
.csv()
```
- name: Aborting requests in-flight
description: |
You can use an [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController) to abort requests. Note that `status` and `statusText` doesn't mean anything for aborted requests, since the request wasn't actually fulfilled.
code: |
```js
const ac = new AbortController()
supabase
.from('very_big_table')
.select()
.abortSignal(ac.signal)
.then(console.log)
ac.abort()
// {
// error: {
// message: 'FetchError: The user aborted a request.',
// details: '',
// hint: '',
// code: ''
// },
// data: null,
// body: null,
// count: null,
// status: 400,
// statusText: 'Bad Request'
// }
```
- id: insert
title: 'Create data: insert()'
$ref: '@supabase/postgrest-js."lib/PostgrestQueryBuilder".PostgrestQueryBuilder.insert'
notes: |
- By default, every time you run `insert()`, the client library will make a `select` to return the full record.
This is convenient, but it can also cause problems if your Policies are not configured to allow the `select` operation.
If you are using Row Level Security and you are encountering problems, try setting the `returning` param to `minimal`.
examples:
- id: create-a-record
name: Create a record
isSpotlight: true
code: |
```js
const { data, error } = await supabase
.from('cities')
.insert([
{ name: 'The Shire', country_id: 554 }
])
```
- id: bulk-create
name: Bulk create
description: |
When running a bulk create, the operation is handled in a single transaction. If any of the inserts fail, all other operations are
rolled back.
code: |
```js
const { data, error } = await supabase
.from('cities')
.insert([
{ name: 'The Shire', country_id: 554 },
{ name: 'Rohan', country_id: 555 },
])
```
- id: upsert
name: Upsert
description: |
For upsert, if set to true, primary key columns would need to be included
in the data parameter in order for an update to properly happen. Also, primary keys
used must be natural, not surrogate. There are however,
[workarounds](https://github.com/PostgREST/postgrest/issues/1118)
for surrogate primary keys.
code: |
```js
const { data, error } = await supabase
.from('cities')
.insert(
[
{ name: 'The Shire', country_id: 554 },
{ name: 'Rohan', country_id: 555 },
{ name: 'City by the Bay', country_id:840}
],
{ upsert: true })
```
- id: update
title: 'Modify data: update()'
$ref: '@supabase/postgrest-js."lib/PostgrestQueryBuilder".PostgrestQueryBuilder.update'
notes: |
- `update()` should always be combined with [Filters](/docs/reference/javascript/using-filters) to target the item(s) you wish to update.
examples:
- id: updating-your-data
name: Updating your data
isSpotlight: true
code: |
```js
const { data, error } = await supabase
.from('cities')
.update({ name: 'Middle Earth' })
.match({ name: 'Auckland' })
```
- id: updating-json-data
name: Updating JSON data
description: |
Postgres offers a
[number of operators](https://www.postgresql.org/docs/current/functions-json.html)
for working with JSON data. Right now it is only possible to update an entire JSON document,
but we are [working on ideas](https://github.com/PostgREST/postgrest/issues/465) for updating individual keys.
code: |
```js
const { data, error } = await supabase
.from('users')
.update(`
address: {
street: 'Melrose Place',
postcode: 90210
}
`)
.eq('address->postcode', 90210)
```
- id: upsert
title: 'Upsert data: upsert()'
$ref: '@supabase/postgrest-js."lib/PostgrestQueryBuilder".PostgrestQueryBuilder.upsert'
notes: |
- Primary keys should be included in the data payload in order for an update to work correctly.
- Primary keys must be natural, not surrogate. There are however, [workarounds](https://github.com/PostgREST/postgrest/issues/1118) for surrogate primary keys.
- If you need to insert new data and update existing data at the same time, use [Postgres triggers](https://github.com/supabase/postgrest-js/issues/173#issuecomment-825124550).
examples:
- id: upsert-your-data
name: Upsert your data
isSpotlight: true
code: |
```js
const { data, error } = await supabase
.from('messages')
.upsert({ id: 3, message: 'foo', username: 'supabot' })