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/apps/docs/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', 'publishable-or-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', 'publishable-or-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', 'publishable-or-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', 'publishable-or-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 signing 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: 'example@email.com', 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: 'example@email.com', 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 sign-in 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: 'example@email.com', 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: 'example@email.com' }) ``` - 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 sign-ins, where the sign-in flow is managed by the Auth server. If you are using email/phone sign-ins 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 signed 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/redirect-urls#use-wildcards-in-redirect-urls) 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 sign-in 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 signed-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 signed-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: 'new@email.com'}) ``` - 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", "publishable-or-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", "publishable-or-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: 'user@email.com', 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: 'user@email.com', 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@example.com') ``` - 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/redirect-urls#use-wildcards-in-redirect-urls) 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', 'email@example.com' ) ``` - 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: 'new@email.com' } ) ``` - 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. 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('characters') .update({ name: 'Han Solo' }) .match({ name: 'Han' }) ``` - 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' }) ``` - id: bulk-upsert-your-data name: Bulk Upsert your data isSpotlight: false code: | ```js const { data, error } = await supabase .from('messages') .upsert([ { id: 3, message: 'foo', username: 'supabot' }, { id: 4, message: 'bar', username: 'supabot' } ]) ``` - id: upserting-into-tables-with-constraints name: Upserting into tables with constraints description: | Running the following will cause supabase to upsert data into the `users` table. If the username 'supabot' already exists, the `onConflict` argument tells supabase to overwrite that row based on the column passed into `onConflict`. isSpotlight: true code: | ```js const { data, error } = await supabase .from('users') .upsert({ username: 'supabot' }, { onConflict: 'username' }) ``` - name: Return the exact number of rows isSpotlight: true code: | ```js const { data, error, count } = await supabase .from('users') .upsert({ id: 3, message: 'foo', username: 'supabot' }, { count: 'exact' }) ``` - id: delete title: 'Delete data: delete()' $ref: '@supabase/postgrest-js."lib/PostgrestQueryBuilder".PostgrestQueryBuilder.delete' notes: | - `delete()` should always be combined with [filters](/docs/reference/javascript/using-filters) to target the item(s) you wish to delete. - If you use `delete()` with filters and you have [RLS](/docs/learn/auth-deep-dive/auth-row-level-security) enabled, only rows visible through `SELECT` policies are deleted. Note that by default no rows are visible, so you need at least one `SELECT`/`ALL` policy that makes the rows visible. examples: - id: delete-records name: Delete records isSpotlight: true code: | ```js const { data, error } = await supabase .from('cities') .delete() .match({ id: 666 }) ``` - id: rpc title: 'Postgres functions: rpc()' description: | You can call Postgres functions as _Remote Procedure Calls_, logic in your database that you can execute from anywhere. Functions are useful when the logic rarely changes—like for password resets and updates. ```sql create or replace function hello_world() returns text as $$ select 'Hello world'; $$ language sql; ``` $ref: '@supabase/postgrest-js."lib/PostgrestRpcBuilder".PostgrestRpcBuilder.rpc' examples: - id: call-a-postgres-function-without-arguments name: Call a Postgres function without arguments isSpotlight: true code: | ```js const { data, error } = await supabase .rpc('hello_world') ``` - id: call-a-postgres-function-with-arguments name: Call a Postgres function with arguments code: | ```js const { data, error } = await supabase .rpc('echo_city', { name: 'The Shire' }) ``` - id: bulk-processing name: Bulk processing description: You can process large payloads at once using [array parameters](https://postgrest.org/en/stable/api.html#calling-functions-with-array-parameters). code: | ```js const { data, error } = await postgrest .rpc('echo_cities', { names: ['The Shire', 'Mordor'] }) ``` - id: call-a-postgres-function-with-filters name: Call a Postgres function with filters description: | Postgres functions that return tables can also be combined with [Modifiers](/docs/reference/javascript/using-modifiers) and [Filters](/docs/reference/javascript/using-filters). code: | ```js const { data, error } = await supabase .rpc('echo_all_cities') .select('name, population') .eq('name', 'The Shire') ``` - id: call-a-postgres-function-with-count-option name: Call a Postgres function with a count option description: | You can specify a count option to get the row count along with your data. Allowed values for count option are `null`, `exact`, `planned` and `estimated`. code: | ```js const { data, error, count } = await supabase .rpc('hello_world', {}, { count: 'exact' }) ``` - id: subscribe title: 'on().subscribe()' $ref: '@supabase/supabase-js.lib/SupabaseQueryBuilder.SupabaseQueryBuilder.on' notes: | - Realtime is disabled by default for new Projects for better database performance and security. You can turn it on by [managing replication](/docs/guides/api). - If you want to receive the "previous" data for updates and deletes, you will need to set `REPLICA IDENTITY` to `FULL`, like this: `ALTER TABLE your_table REPLICA IDENTITY FULL;` examples: - id: listen-to-all-database-changes name: Listen to all database changes isSpotlight: true code: | ```js const mySubscription = supabase .from('*') .on('*', payload => { console.log('Change received!', payload) }) .subscribe() ``` - id: listen-to-a-specific-table name: Listen to a specific table code: | ```js const mySubscription = supabase .from('countries') .on('*', payload => { console.log('Change received!', payload) }) .subscribe() ``` - id: listen-to-inserts name: Listen to inserts code: | ```js const mySubscription = supabase .from('countries') .on('INSERT', payload => { console.log('Change received!', payload) }) .subscribe() ``` - id: listen-to-updates name: Listen to updates description: | By default, Supabase will send only the updated record. If you want to receive the previous values as well you can enable full replication for the table you are listening too: ```sql alter table "your_table" replica identity full; ``` code: | ```js const mySubscription = supabase .from('countries') .on('UPDATE', payload => { console.log('Change received!', payload) }) .subscribe() ``` - id: listen-to-deletes name: Listen to deletes description: | By default, Supabase does not send deleted records. If you want to receive the deleted record you can enable full replication for the table you are listening too: ```sql alter table "your_table" replica identity full; ``` code: | ```js const mySubscription = supabase .from('countries') .on('DELETE', payload => { console.log('Change received!', payload) }) .subscribe() ``` - id: listen-to-multiple-events name: Listen to multiple events description: You can chain listeners if you want to listen to multiple events for each table. code: | ```js const mySubscription = supabase .from('countries') .on('INSERT', handleRecordInserted) .on('DELETE', handleRecordDeleted) .subscribe() ``` - id: listening-to-row-level-changes name: Listen to row level changes description: You can listen to individual rows using the format `{table}:{col}=eq.{val}` - where `{col}` is the column name, and `{val}` is the value which you want to match. notes: | - ``eq`` filter works with all database types as under the hood, it's casting both the filter value and the database value to the correct type and then comparing them. code: | ```js const mySubscription = supabase .from('countries:id=eq.200') .on('UPDATE', handleRecordUpdated) .subscribe() ``` - id: remove-subscription title: 'removeSubscription()' $ref: '@supabase/supabase-js.index.SupabaseClient.removeSubscription' notes: | - Removing subscriptions is a great way to maintain the performance of your project's database. Supabase will automatically handle cleanup 30 seconds after a user is disconnected, but unused subscriptions may cause degradation as more users are simultaneously subscribed. examples: - id: remove-a-subscription name: Remove a subscription isSpotlight: true code: | ```js supabase.removeSubscription(mySubscription) ``` - id: remove-all-subscriptions title: 'removeAllSubscriptions()' $ref: '@supabase/supabase-js.index.SupabaseClient.removeAllSubscriptions' notes: | - Removing subscriptions is a great way to maintain the performance of your project's database. Supabase will automatically handle cleanup 30 seconds after a user is disconnected, but unused subscriptions may cause degradation as more users are simultaneously subscribed. examples: - id: removes-all-subscriptions name: Removes all subscriptions isSpotlight: true code: | ```js supabase.removeAllSubscriptions() ``` - id: get-subscriptions title: 'getSubscriptions()' $ref: '@supabase/supabase-js.index.SupabaseClient.getSubscriptions' examples: - id: get-all-subscriptions name: Get all subscriptions isSpotlight: true code: | ```js const subscriptions = supabase.getSubscriptions() ``` - id: file-buckets title: 'Overview' notes: | This section contains methods for working with File Buckets. # - id: analytics-buckets # title: 'Overview' # notes: | # This section contains methods for working with Analytics Buckets. # - id: vector-buckets # title: 'Overview' # notes: | # This section contains methods for working with Vector Buckets. - id: list-buckets title: 'listBuckets()' $ref: '@supabase/storage-js."lib/StorageBucketApi".StorageBucketApi.listBuckets' notes: | - Policy permissions required: - `buckets` permissions: `select` - `objects` permissions: none examples: - id: list-buckets name: List buckets isSpotlight: true code: | ```ts const { data, error } = await supabase .storage .listBuckets() ``` - id: get-bucket title: 'getBucket()' $ref: '@supabase/storage-js."lib/StorageBucketApi".StorageBucketApi.getBucket' notes: | - Policy permissions required: - `buckets` permissions: `select` - `objects` permissions: none examples: - id: get-bucket name: Get bucket isSpotlight: true code: | ```js const { data, error } = await supabase .storage .getBucket('avatars') ``` - id: create-bucket title: 'createBucket()' $ref: '@supabase/storage-js."lib/StorageBucketApi".StorageBucketApi.createBucket' notes: | - Policy permissions required: - `buckets` permissions: `insert` - `objects` permissions: none examples: - id: create-bucket name: Create bucket isSpotlight: true code: | ```js const { data, error } = await supabase .storage .createBucket('avatars', { public: false }) ``` - id: empty-bucket title: 'emptyBucket()' $ref: '@supabase/storage-js."lib/StorageBucketApi".StorageBucketApi.emptyBucket' notes: | - Policy permissions required: - `buckets` permissions: `select` - `objects` permissions: `select` and `delete` examples: - id: empty-bucket name: Empty bucket isSpotlight: true code: | ```js const { data, error } = await supabase .storage .emptyBucket('avatars') ``` - id: update-bucket title: 'updateBucket()' $ref: '@supabase/storage-js."lib/StorageBucketApi".StorageBucketApi.updateBucket' notes: | - Policy permissions required: - `buckets` permissions: `update` - `objects` permissions: none examples: - id: update-bucket name: Update bucket isSpotlight: true code: | ```js const { data, error } = await supabase .storage .updateBucket('avatars', { public: false }) ``` - id: delete-bucket title: 'deleteBucket()' $ref: '@supabase/storage-js."lib/StorageBucketApi".StorageBucketApi.deleteBucket' notes: | - Policy permissions required: - `buckets` permissions: `select` and `delete` - `objects` permissions: none examples: - id: delete-bucket name: Delete bucket isSpotlight: true code: | ```js const { data, error } = await supabase .storage .deleteBucket('avatars') ``` - id: from-upload title: 'from.upload()' $ref: '@supabase/storage-js."lib/StorageFileApi".StorageFileApi.upload' notes: | - Policy permissions required: - `buckets` permissions: none - `objects` permissions: `insert` - For React Native, using either `Blob`, `File` or `FormData` does not work as intended. Upload file using `ArrayBuffer` from base64 file data instead, see example below. examples: - id: upload-file name: Upload file isSpotlight: true code: | ```js const avatarFile = event.target.files[0] const { data, error } = await supabase .storage .from('avatars') .upload('public/avatar1.png', avatarFile, { cacheControl: '3600', upsert: false }) ``` - id: upload-file-using-arraybuffer-from-base64-file-data name: Upload file using `ArrayBuffer` from base64 file data code: | ```js import { decode } from 'base64-arraybuffer' const { data, error } = await supabase .storage .from('avatars') .upload('public/avatar1.png', decode('base64FileData'), { contentType: 'image/png' }) ``` - id: from-update title: 'from.update()' $ref: '@supabase/storage-js."lib/StorageFileApi".StorageFileApi.update' notes: | - Policy permissions required: - `buckets` permissions: none - `objects` permissions: `update` and `select` - For React Native, using either `Blob`, `File` or `FormData` does not work as intended. Update file using `ArrayBuffer` from base64 file data instead, see example below. examples: - id: update-file name: Update file isSpotlight: true code: | ```js const avatarFile = event.target.files[0] const { data, error } = await supabase .storage .from('avatars') .update('public/avatar1.png', avatarFile, { cacheControl: '3600', upsert: false }) ``` - id: update-file-using-arraybuffer-from-base64-file-data name: Update file using `ArrayBuffer` from base64 file data code: | ```js import {decode} from 'base64-arraybuffer' const { data, error } = await supabase .storage .from('avatars') .update('public/avatar1.png', decode('base64FileData'), { contentType: 'image/png' }) ``` - id: from-move title: 'from.move()' $ref: '@supabase/storage-js."lib/StorageFileApi".StorageFileApi.move' notes: | - Policy permissions required: - `buckets` permissions: none - `objects` permissions: `update` and `select` examples: - id: move-file name: Move file isSpotlight: true code: | ```js const { data, error } = await supabase .storage .from('avatars') .move('public/avatar1.png', 'private/avatar2.png') ``` - id: from-copy title: 'from.copy()' $ref: '@supabase/storage-js."lib/StorageFileApi".StorageFileApi.copy' notes: | - Policy permissions required: - `buckets` permissions: none - `objects` permissions: `insert` and `select` examples: - id: copy-file name: Copy file isSpotlight: true code: | ```js const { data, error } = await supabase .storage .from('avatars') .copy('public/avatar1.png', 'private/avatar2.png') ``` - id: from-create-signed-url title: 'from.createSignedUrl()' $ref: '@supabase/storage-js."lib/StorageFileApi".StorageFileApi.createSignedUrl' notes: | - Policy permissions required: - `buckets` permissions: none - `objects` permissions: `select` examples: - id: create-signed-url name: Create Signed URL isSpotlight: true code: | ```js const { signedURL, error } = await supabase .storage .from('avatars') .createSignedUrl('folder/avatar1.png', 60) ``` - id: from-create-signed-urls title: 'from.createSignedUrls()' $ref: '@supabase/storage-js."lib/StorageFileApi".StorageFileApi.createSignedUrls' notes: | - Policy permissions required: - `buckets` permissions: none - `objects` permissions: `select` examples: - id: create-signed-urls name: Create Signed URLs isSpotlight: true code: | ```js const { data, error } = await supabase .storage .from('avatars') .createSignedUrls(['folder/avatar1.png', 'folder/avatar2.png'], 60) ``` - id: from-get-public-url title: 'from.getPublicUrl()' $ref: '@supabase/storage-js."lib/StorageFileApi".StorageFileApi.getPublicUrl' notes: | - The bucket needs to be set to public, either via [updateBucket()](/docs/reference/javascript/storage-updatebucket) or by going to Storage on [supabase.com/dashboard](https://supabase.com/dashboard), clicking the overflow menu on a bucket and choosing "Make public" - Policy permissions required: - `buckets` permissions: none - `objects` permissions: none examples: - id: returns-the-url-for-an-asset-in-a-public-bucket name: Returns the URL for an asset in a public bucket isSpotlight: true code: | ```js const { publicURL, error } = supabase .storage .from('public-bucket') .getPublicUrl('folder/avatar1.png') ``` - id: from-download title: 'from.download()' $ref: '@supabase/storage-js."lib/StorageFileApi".StorageFileApi.download' notes: | - Policy permissions required: - `buckets` permissions: none - `objects` permissions: `select` examples: - id: download-file name: Download file isSpotlight: true code: | ```js const { data, error } = await supabase .storage .from('avatars') .download('folder/avatar1.png') ``` - id: from-remove title: 'from.remove()' $ref: '@supabase/storage-js."lib/StorageFileApi".StorageFileApi.remove' notes: | - Policy permissions required: - `buckets` permissions: none - `objects` permissions: `delete` and `select` examples: - id: delete-file name: Delete file isSpotlight: true code: | ```js const { data, error } = await supabase .storage .from('avatars') .remove(['folder/avatar1.png']) ``` - id: from-list title: 'from.list()' $ref: '@supabase/storage-js."lib/StorageFileApi".StorageFileApi.list' notes: | - Policy permissions required: - `buckets` permissions: none - `objects` permissions: `select` examples: - id: list-files-in-a-bucket name: List files in a bucket isSpotlight: true code: | ```js const { data, error } = await supabase .storage .from('avatars') .list('folder', { limit: 100, offset: 0, sortBy: { column: 'name', order: 'asc' }, }) ``` - id: search-files-in-a-bucket name: Search files in a bucket code: | ```js const { data, error } = await supabase .storage .from('avatars') .list('folder', { limit: 100, offset: 0, sortBy: { column: 'name', order: 'asc' }, search: 'jon' }) ``` - id: using-modifiers title: Using Modifiers description: | Modifiers can be used on `select()` queries. If a Postgres function returns a table response, you can also apply modifiers to the `rpc()` function. - id: limit title: limit() $ref: '@supabase/postgrest-js."lib/PostgrestFilterBuilder".PostgrestFilterBuilder.limit' examples: - id: with-select name: With `select()` isSpotlight: true code: | ```js const { data, error } = await supabase .from('cities') .select('name, country_id') .limit(1) ``` - id: with-embedded-resources name: With embedded resources code: | ```js const { data, error } = await supabase .from('countries') .select('name, cities(name)') .eq('name', 'The Shire') .limit(1, { foreignTable: 'cities' }) ``` - id: order title: order() $ref: '@supabase/postgrest-js."lib/PostgrestFilterBuilder".PostgrestFilterBuilder.order' examples: - id: with-select name: With `select()` isSpotlight: true code: | ```js const { data, error } = await supabase .from('cities') .select('name, country_id') .order('id', { ascending: false }) ``` - id: with-embedded-resources name: With embedded resources code: | ```js const { data, error } = await supabase .from('countries') .select('name, cities(name)') .eq('name', 'The Shire') .order('name', {foreignTable: 'cities'}) ``` - id: ordering-multiple-columns name: Ordering multiple columns code: | ```js const { data, error } = await supabase .from('cities') .select('name', 'country_id') .order('country_id', { ascending: false }) .order('name', { ascending: false }) ``` - id: range title: range() $ref: '@supabase/postgrest-js."lib/PostgrestFilterBuilder".PostgrestFilterBuilder.range' examples: - id: with-select name: With `select()` isSpotlight: true code: | ```js const { data, error } = await supabase .from('cities') .select('name, country_id') .range(0,3) ``` - id: single title: single() $ref: '@supabase/postgrest-js."lib/PostgrestFilterBuilder".PostgrestFilterBuilder.single' examples: - id: with-select name: With `select()` isSpotlight: true code: | ```js const { data, error } = await supabase .from('cities') .select('name, country_id') .limit(1) .single() ``` - id: maybe-single title: maybeSingle() $ref: '@supabase/postgrest-js."lib/PostgrestFilterBuilder".PostgrestFilterBuilder.maybeSingle' examples: - id: with-select name: With `select()` isSpotlight: true code: | ```js const { data, error } = await supabase .from('instruments') .select('name, section_id') .eq('name', 'violin') .maybeSingle() ``` - id: using-filters title: Using Filters description: | Filters can be used on `select()`, `update()`, and `delete()` queries. If a Postgres function returns a table response, you can also apply filters. ### Applying Filters You must apply your filters to the end of your query. For example: ```js const { data, error } = await supabase .from('cities') .select('name, country_id') .eq('name', 'The Shire') // Correct const { data, error } = await supabase .from('cities') .eq('name', 'The Shire') // Incorrect .select('name, country_id') ``` ### Chaining Filters can be chained together to produce advanced queries. For example: ```js const { data, error } = await supabase .from('cities') .select('name, country_id') .gte('population', 1000) .lt('population', 10000) ``` ### Conditional Chaining Filters can be built up one step at a time and then executed. For example: ```js const filterByName = null const filterPopLow = 1000 const filterPopHigh = 10000 let query = supabase .from('cities') .select('name, country_id') if (filterByName) { query = query.eq('name', filterByName) } if (filterPopLow) { query = query.gte('population', filterPopLow) } if (filterPopHigh) { query = query.lt('population', filterPopHigh) } const { data, error } = await query ``` - id: or title: or() $ref: '@supabase/postgrest-js."lib/PostgrestFilterBuilder".PostgrestFilterBuilder.or' notes: | - `.or()` expects you to use the raw [PostgREST syntax](https://postgrest.org/en/stable/api.html#horizontal-filtering-rows) for the filter names and values. ```js .or('id.in.(6,7), arraycol.cs.{"a","b"}') // Use Postgres list () for in filter. Array {} for array column and 'cs' for contains. .or(`id.in.(${arrList}),arraycol.cs.{${arr}}`) // You can insert a javascipt array for list or array on array column. .or(`id.in.(${arrList}),rangecol.cs.[${arrRange})`) // You can insert a javascipt array for list or range on a range column. ``` examples: - id: with-select name: With `select()` isSpotlight: true code: | ```js const { data, error } = await supabase .from('cities') .select('name, country_id') .or('id.eq.20,id.eq.30') ``` - id: use-or-with-and name: Use `or` with `and` isSpotlight: true code: | ```js const { data, error } = await supabase .from('characters') .select('name, book_id') .or('id.gt.20,and(name.eq.Harry,name.eq.Frodo)') ``` - id: use-or-on-foreign-tables name: Use `or` on foreign tables isSpotlight: true code: | ```js const { data, error } = await supabase .from('books') .select('id, characters(*)') .or('name.eq.Luke,name.eq.Leia', { foreignTable: "characters" }) ``` - id: not title: not() $ref: '@supabase/postgrest-js."lib/PostgrestFilterBuilder".PostgrestFilterBuilder.not' notes: | - `.not()` expects you to use the raw [PostgREST syntax](https://postgrest.org/en/stable/api.html#horizontal-filtering-rows) for the filter names and values. ```js .not('name','eq','Luke') .not('arraycol','cs','{"a","b"}') // Use Postgres array {} for array column and 'cs' for contains. .not('rangecol','cs','(1,2]') // Use Postgres range syntax for range column. .not('id','in','(6,7)') // Use Postgres list () for in filter. .not('id','in',`(${arr})`) // You can insert a javascript array. ``` examples: - id: with-select name: With `select()` isSpotlight: true code: | ```js const { data, error } = await supabase .from('countries') .select('name, country_id') .not('name', 'eq', 'The Shire') ``` - id: with-update name: With `update()` code: | ```js const { data, error } = await supabase .from('countries') .update({ name: 'Mordor' }) .not('name', 'eq', 'Rohan') ``` - id: with-delete name: With `delete()` code: | ```js const { data, error } = await supabase .from('countries') .delete() .not('name', 'eq', 'The Shire') ``` - id: with-rpc name: With `rpc()` code: | ```js // Only valid if the Postgres function returns a table type. const { data, error } = await supabase .rpc('echo_all_countries') .not('name', 'eq', 'The Shire') ``` - id: match title: match() $ref: '@supabase/postgrest-js."lib/PostgrestFilterBuilder".PostgrestFilterBuilder.match' examples: - id: with-select name: With `select()` isSpotlight: true code: | ```js const { data, error } = await supabase .from('characters') .select('name, book_id') .match({name: 'Harry', book_id: 156}) ``` - id: with-update name: With `update()` code: | ```js const { data, error } = await supabase .from('instruments') .update({ name: 'piano' }) .match({name: 'harpsichord', section_id: 2}) ``` - id: with-delete name: With `delete()` code: | ```js const { data, error } = await supabase .from('countries') .delete() .match({name: 'The Shire', country_id: 156}) ``` - id: with-rpc name: With `rpc()` code: | ```js // Only valid if the Postgres function returns a table type. const { data, error } = await supabase .rpc('echo_all_characters') .match({name: 'Frodo', book_id: 156}) ``` - id: eq title: eq() $ref: '@supabase/postgrest-js."lib/PostgrestFilterBuilder".PostgrestFilterBuilder.eq' examples: - id: with-select name: With `select()` isSpotlight: true code: | ```js const { data, error } = await supabase .from('cities') .select('name, country_id') .eq('name', 'The shire') ``` - id: with-update name: With `update()` code: | ```js const { data, error } = await supabase .from('countries') .update({ name: 'Mordor' }) .eq('name', 'Rohan') ``` - id: with-delete name: With `delete()` code: | ```js const { data, error } = await supabase .from('countries') .delete() .eq('name', 'Mordor') ``` - id: with-rpc name: With `rpc()` code: | ```js // Only valid if the Postgres function returns a table type. const { data, error } = await supabase .rpc('echo_all_countries') .eq('name', 'Mordor') ``` - id: neq title: neq() $ref: '@supabase/postgrest-js."lib/PostgrestFilterBuilder".PostgrestFilterBuilder.neq' examples: - id: with-select name: With `select()` isSpotlight: true code: | ```js const { data, error } = await supabase .from('cities') .select('name, country_id') .neq('name', 'The shire') ``` - id: with-update name: With `update()` code: | ```js const { data, error } = await supabase .from('countries') .update({ name: 'Mordor' }) .neq('name', 'Gondor') ``` - id: with-delete name: With `delete()` code: | ```js const { data, error } = await supabase .from('countries') .delete() .neq('name', 'Mordor') ``` - id: with-rpc name: With `rpc()` code: | ```js // Only valid if the Postgres function returns a table type. const { data, error } = await supabase .rpc('echo_all_countries') .neq('name', 'Mordor') ``` - id: gt title: gt() $ref: '@supabase/postgrest-js."lib/PostgrestFilterBuilder".PostgrestFilterBuilder.gt' examples: - id: with-select name: With `select()` isSpotlight: true code: | ```js const { data, error } = await supabase .from('cities') .select('name, country_id') .gt('country_id', 250) ``` - id: with-update name: With `update()` code: | ```js const { data, error } = await supabase .from('cities') .update({ name: 'Mordor' }) .gt('country_id', 250) ``` - id: with-delete name: With `delete()` code: | ```js const { data, error } = await supabase .from('cities') .delete() .gt('country_id', 250) ``` - id: with-rpc name: With `rpc()` code: | ```js // Only valid if the Postgres function returns a table type. const { data, error } = await supabase .rpc('echo_all_cities') .gt('country_id', 250) ``` - id: gte title: gte() $ref: '@supabase/postgrest-js."lib/PostgrestFilterBuilder".PostgrestFilterBuilder.gte' examples: - id: with-select name: With `select()` isSpotlight: true code: | ```js const { data, error } = await supabase .from('cities') .select('name, country_id') .gte('country_id', 250) ``` - id: with-update name: With `update()` code: | ```js const { data, error } = await supabase .from('cities') .update({ name: 'Mordor' }) .gte('country_id', 250) ``` - id: with-delete name: With `delete()` code: | ```js const { data, error } = await supabase .from('cities') .delete() .gte('country_id', 250) ``` - id: with-rpc name: With `rpc()` code: | ```js // Only valid if the Postgres function returns a table type. const { data, error } = await supabase .rpc('echo_all_cities') .gte('country_id', 250) ``` - id: lt title: lt() $ref: '@supabase/postgrest-js."lib/PostgrestFilterBuilder".PostgrestFilterBuilder.lt' examples: - id: with-select name: With `select()` isSpotlight: true code: | ```js const { data, error } = await supabase .from('cities') .select('name, country_id') .lt('country_id', 250) ``` - id: with-update name: With `update()` code: | ```js const { data, error } = await supabase .from('cities') .update({ name: 'Mordor' }) .lt('country_id', 250) ``` - id: with-delete name: With `delete()` code: | ```js const { data, error } = await supabase .from('cities') .delete() .lt('country_id', 250) ``` - id: with-rpc name: With `rpc()` code: | ```js // Only valid if the Postgres function returns a table type. const { data, error } = await supabase .rpc('echo_all_cities') .lt('country_id', 250) ``` - id: lte title: lte() $ref: '@supabase/postgrest-js."lib/PostgrestFilterBuilder".PostgrestFilterBuilder.lte' examples: - id: with-select name: With `select()` isSpotlight: true code: | ```js const { data, error } = await supabase .from('cities') .select('name, country_id') .lte('country_id', 250) ``` - id: with-update name: With `update()` code: | ```js const { data, error } = await supabase .from('cities') .update({ name: 'Mordor' }) .lte('country_id', 250) ``` - id: with-delete name: With `delete()` code: | ```js const { data, error } = await supabase .from('cities') .delete() .lte('country_id', 250) ``` - id: with-rpc name: With `rpc()` code: | ```js // Only valid if the Postgres function returns a table type. const { data, error } = await supabase .rpc('echo_all_cities') .lte('country_id', 250) ``` - id: like title: like() $ref: '@supabase/postgrest-js."lib/PostgrestFilterBuilder".PostgrestFilterBuilder.like' examples: - id: with-select name: With `select()` isSpotlight: true code: | ```js const { data, error } = await supabase .from('cities') .select('name, country_id') .like('name', '%la%') ``` - id: with-update name: With `update()` code: | ```js const { data, error } = await supabase .from('cities') .update({ name: 'Mordor' }) .like('name', '%la%') ``` - id: with-delete name: With `delete()` code: | ```js const { data, error } = await supabase .from('cities') .delete() .like('name', '%la%') ``` - id: with-rpc name: With `rpc()` code: | ```js // Only valid if the Postgres function returns a table type. const { data, error } = await supabase .rpc('echo_all_cities') .like('name', '%la%') ``` - id: ilike title: ilike() $ref: '@supabase/postgrest-js."lib/PostgrestFilterBuilder".PostgrestFilterBuilder.ilike' examples: - id: with-select name: With `select()` isSpotlight: true code: | ```js const { data, error } = await supabase .from('cities') .select('name, country_id') .ilike('name', '%la%') ``` - id: with-update name: With `update()` code: | ```js const { data, error } = await supabase .from('cities') .update({ name: 'Mordor' }) .ilike('name', '%la%') ``` - id: with-delete name: With `delete()` code: | ```js const { data, error } = await supabase .from('cities') .delete() .ilike('name', '%la%') ``` - id: with-rpc name: With `rpc()` code: | ```js // Only valid if the Postgres function returns a table type. const { data, error } = await supabase .rpc('echo_all_cities') .ilike('name', '%la%') ``` - id: is title: is() $ref: '@supabase/postgrest-js."lib/PostgrestFilterBuilder".PostgrestFilterBuilder.is' examples: - id: with-select name: With `select()` isSpotlight: true code: | ```js const { data, error } = await supabase .from('cities') .select('name, country_id') .is('name', null) ``` - id: with-update name: With `update()` code: | ```js const { data, error } = await supabase .from('cities') .update({ name: 'Mordor' }) .is('name', null) ``` - id: with-delete name: With `delete()` code: | ```js const { data, error } = await supabase .from('cities') .delete() .is('name', null) ``` - id: with-rpc name: With `rpc()` code: | ```js // Only valid if the Postgres function returns a table type. const { data, error } = await supabase .rpc('echo_all_cities') .is('name', null) ``` - id: in title: in() $ref: '@supabase/postgrest-js."lib/PostgrestFilterBuilder".PostgrestFilterBuilder.in' examples: - id: with-select name: With `select()` isSpotlight: true code: | ```js const { data, error } = await supabase .from('characters') .select('name, book_id') .in('name', ['Harry', 'Hermione']) ``` - id: with-update name: With `update()` code: | ```js const { data, error } = await supabase .from('countries') .update({ name: 'Mordor' }) .in('name', ['Gondor', 'Rohan']) ``` - id: with-delete name: With `delete()` code: | ```js const { data, error } = await supabase .from('characters') .delete() .in('name', ['Dumbledore', 'Snape']) ``` - id: with-rpc name: With `rpc()` code: | ```js // Only valid if the Postgres function returns a table type. const { data, error } = await supabase .rpc('echo_all_characters') .in('name', ['Luke', 'Leia']) ``` - id: contains title: contains() $ref: '@supabase/postgrest-js."lib/PostgrestFilterBuilder".PostgrestFilterBuilder.contains' notes: | - `.contains()` can work on array columns or range columns. It is very useful for finding rows where a tag array contains all the values in the filter array. ```js .contains('arraycol',["a","b"]) // You can use a javascript array for an array column .contains('arraycol','{"a","b"}') // You can use a string with Postgres array {} for array column. .contains('rangecol','(1,2]') // Use Postgres range syntax for range column. .contains('rangecol',`(${arr}]`) // You can insert an array into a string. ``` examples: - id: with-select name: With `select()` isSpotlight: true code: | ```js const { data, error } = await supabase .from('countries') .select('name, id, main_exports') .contains('main_exports', ['oil']) ``` - id: with-update name: With `update()` code: | ```js const { data, error } = await supabase .from('countries') .update({ name: 'Mordor' }) .contains('main_exports', ['oil']) ``` - id: with-delete name: With `delete()` code: | ```js const { data, error } = await supabase .from('countries') .delete() .contains('main_exports', ['oil']) ``` - id: with-rpc name: With `rpc()` code: | ```js // Only valid if the Postgres function returns a table type. const { data, error } = await supabase .rpc('echo_all_countries') .contains('main_exports', ['oil']) ``` - id: contained-by title: containedBy() $ref: '@supabase/postgrest-js."lib/PostgrestFilterBuilder".PostgrestFilterBuilder.containedBy' notes: | - `.containedBy()` can work on array columns or range columns. ```js .containedBy('arraycol',["a","b"]) // You can use a javascript array for an array column .containedBy('arraycol','{"a","b"}') // You can use a string with Postgres array {} for array column. .containedBy('rangecol','(1,2]') // Use Postgres range syntax for range column. .containedBy('rangecol',`(${arr}]`) // You can insert an array into a string. ``` examples: - id: with-select name: With `select()` isSpotlight: true code: | ```js const { data, error } = await supabase .from('countries') .select('name, id, main_exports') .containedBy('main_exports', ['cars', 'food', 'machine']) ``` - id: with-update name: With `update()` code: | ```js const { data, error } = await supabase .from('countries') .update({ name: 'Mordor' }) .containedBy('main_exports', ['orks', 'surveillance', 'evil']) ``` - id: with-delete name: With `delete()` code: | ```js const { data, error } = await supabase .from('countries') .delete() .containedBy('main_exports', ['cars', 'food', 'machine']) ``` - id: with-rpc name: With `rpc()` code: | ```js // Only valid if the Postgres function returns a table type. const { data, error } = await supabase .rpc('echo_all_countries') .containedBy('main_exports', ['cars', 'food', 'machine']) ``` - id: range-lte title: rangeLte() $ref: '@supabase/postgrest-js."lib/PostgrestFilterBuilder".PostgrestFilterBuilder.rangeLt' examples: - id: with-select name: With `select()` isSpotlight: true code: | ```js const { data, error } = await supabase .from('countries') .select('name, id, population_range_millions') .rangeLt('population_range_millions', '[150, 250]') ``` - id: with-update name: With `update()` code: | ```js const { data, error } = await supabase .from('countries') .update({ name: 'Mordor' }) .rangeLt('population_range_millions', '[150, 250]') ``` - id: with-delete name: With `delete()` code: | ```js const { data, error } = await supabase .from('countries') .delete() .rangeLt('population_range_millions', '[150, 250]') ``` - id: with-rpc name: With `rpc()` code: | ```js // Only valid if the Postgres function returns a table type. const { data, error } = await supabase .rpc('echo_all_countries') .rangeLt('population_range_millions', '[150, 250]') ``` - id: range-gt title: rangeGt() $ref: '@supabase/postgrest-js."lib/PostgrestFilterBuilder".PostgrestFilterBuilder.rangeGt' examples: - id: with-select name: With `select()` isSpotlight: true code: | ```js const { data, error } = await supabase .from('countries') .select('name, id, population_range_millions') .rangeGt('population_range_millions', '[150, 250]') ``` - id: with-update name: With `update()` code: | ```js const { data, error } = await supabase .from('countries') .update({ name: 'Mordor' }) .rangeGt('population_range_millions', '[150, 250]') ``` - id: with-delete name: With `delete()` code: | ```js const { data, error } = await supabase .from('countries') .delete() .rangeGt('population_range_millions', '[150, 250]') ``` - id: with-rpc name: With `rpc()` code: | ```js // Only valid if the Postgres function returns a table type. const { data, error } = await supabase .rpc('echo_all_countries') .rangeGt('population_range_millions', '[150, 250]') ``` - id: range-gte title: rangeGte() $ref: '@supabase/postgrest-js."lib/PostgrestFilterBuilder".PostgrestFilterBuilder.rangeGte' examples: - id: with-select name: With `select()` isSpotlight: true code: | ```js const { data, error } = await supabase .from('countries') .select('name, id, population_range_millions') .rangeGte('population_range_millions', '[150, 250]') ``` - id: with-update name: With `update()` code: | ```js const { data, error } = await supabase .from('countries') .update({ name: 'Mordor' }) .rangeGte('population_range_millions', '[150, 250]') ``` - id: with-delete name: With `delete()` code: | ```js const { data, error } = await supabase .from('countries') .delete() .rangeGte('population_range_millions', '[150, 250]') ``` - id: with-rpc name: With `rpc()` code: | ```js // Only valid if the Postgres function returns a table type. const { data, error } = await supabase .rpc('echo_all_countries') .rangeGte('population_range_millions', '[150, 250]') ``` - id: range-lte title: rangeLte() $ref: '@supabase/postgrest-js."lib/PostgrestFilterBuilder".PostgrestFilterBuilder.rangeLte' examples: - id: with-select name: With `select()` isSpotlight: true code: | ```js const { data, error } = await supabase .from('countries') .select('name, id, population_range_millions') .rangeLte('population_range_millions', '[150, 250]') ``` - id: with-update name: With `update()` code: | ```js const { data, error } = await supabase .from('countries') .update({ name: 'Mordor' }) .rangeLte('population_range_millions', '[150, 250]') ``` - id: with-delete name: With `delete()` code: | ```js const { data, error } = await supabase .from('countries') .delete() .rangeLte('population_range_millions', '[150, 250]') ``` - id: with-rpc name: With `rpc()` code: | ```js // Only valid if the Postgres function returns a table type. const { data, error } = await supabase .rpc('echo_all_countries') .rangeLte('population_range_millions', '[150, 250]') ``` - id: range-adjacent title: rangeAdjacent() $ref: '@supabase/postgrest-js."lib/PostgrestFilterBuilder".PostgrestFilterBuilder.rangeAdjacent' examples: - id: with-select name: With `select()` isSpotlight: true code: | ```js const { data, error } = await supabase .from('countries') .select('name, id, population_range_millions') .rangeAdjacent('population_range_millions', '[70, 185]') ``` - id: with-update name: With `update()` code: | ```js const { data, error } = await supabase .from('countries') .update({ name: 'Mordor' }) .rangeAdjacent('population_range_millions', '[70, 185]') ``` - id: with-delete name: With `delete()` code: | ```js const { data, error } = await supabase .from('countries') .delete() .rangeAdjacent('population_range_millions', '[70, 185]') ``` - id: with-rpc name: With `rpc()` code: | ```js // Only valid if the Postgres function returns a table type. const { data, error } = await supabase .rpc('echo_all_countries') .rangeAdjacent('population_range_millions', '[70, 185]') ``` - id: overlaps title: overlaps() $ref: '@supabase/postgrest-js."lib/PostgrestFilterBuilder".PostgrestFilterBuilder.overlaps' notes: | - `.overlaps()` can work on array columns or range columns. ```js .overlaps('arraycol',["a","b"]) // You can use a javascript array for an array column .overlaps('arraycol','{"a","b"}') // You can use a string with Postgres array {} for array column. .overlaps('rangecol','(1,2]') // Use Postgres range syntax for range column. .overlaps('rangecol',`(${arr}]`) // You can insert an array into a string. ``` examples: - id: with-select name: With `select()` isSpotlight: true code: | ```js const { data, error } = await supabase .from('countries') .select('name, id, main_exports') .overlaps('main_exports', ['computers', 'minerals']) ``` - id: with-update name: With `update()` code: | ```js let countries = await supabase .from('countries') .update({ name: 'Mordor' }) .overlaps('main_exports', ['computers', 'minerals']) ``` - id: with-delete name: With `delete()` code: | ```js const { data, error } = await supabase .from('countries') .delete() .overlaps('main_exports', ['computers', 'minerals']) ``` - id: with-rpc name: With `rpc()` code: | ```js // Only valid if the Postgres function returns a table type. const { data, error } = await supabase .rpc('echo_all_countries') .overlaps('main_exports', ['computers', 'minerals']) ``` - id: text-search title: textSearch() $ref: '@supabase/postgrest-js."lib/PostgrestFilterBuilder".PostgrestFilterBuilder.textSearch' examples: - id: text-search name: Text search code: | ```js const { data, error } = await supabase .from('quotes') .select('catchphrase') .textSearch('catchphrase', `'fat' & 'cat'`, { config: 'english' }) ``` - id: basic-normalization name: Basic normalization description: Uses PostgreSQL's `plainto_tsquery` function. code: | ```js const { data, error } = await supabase .from('quotes') .select('catchphrase') .textSearch('catchphrase', `'fat' & 'cat'`, { type: 'plain', config: 'english' }) ``` - id: full-normalization name: Full normalization description: Uses PostgreSQL's `phraseto_tsquery` function. code: | ```js const { data, error } = await supabase .from('quotes') .select('catchphrase') .textSearch('catchphrase', `'fat' & 'cat'`, { type: 'phrase', config: 'english' }) ``` - id: web-search name: Websearch description: | Uses PostgreSQL's `websearch_to_tsquery` function. This function will never raise syntax errors, which makes it possible to use raw user-supplied input for search, and can be used with advanced operators. - `unquoted text`: text not inside quote marks will be converted to terms separated by & operators, as if processed by plainto_tsquery. - `"quoted text"`: text inside quote marks will be converted to terms separated by `<->` operators, as if processed by phraseto_tsquery. - `OR`: the word “or” will be converted to the | operator. - `-`: a dash will be converted to the ! operator. code: | ```js const { data, error } = await supabase .from('quotes') .select('catchphrase') .textSearch('catchphrase', `'fat or cat'`, { type: 'websearch', config: 'english' }) ``` - id: filter title: filter() $ref: '@supabase/postgrest-js."lib/PostgrestFilterBuilder".PostgrestFilterBuilder.filter' notes: | - `.filter()` expects you to use the raw [PostgREST syntax](https://postgrest.org/en/stable/api.html#horizontal-filtering-rows) for the filter names and values, so it should only be used as an escape hatch in case other filters don't work. ```js .filter('arraycol','cs','{"a","b"}') // Use Postgres array {} for array column and 'cs' for contains. .filter('rangecol','cs','(1,2]') // Use Postgres range syntax for range column. .filter('id','in','(6,7)') // Use Postgres list () for in filter. .filter('id','in',`(${arr})`) // You can insert a javascript array. ``` examples: - id: with-select name: With `select()` isSpotlight: true code: | ```js const { data, error } = await supabase .from('characters') .select('name, book_id') .filter('name', 'in', '("Harry","Hermione")') ``` - id: with-update name: With `update()` code: | ```js const { data, error } = await supabase .from('countries') .update({ name: 'Mordor' }) .filter('name', 'in', '("Gondor","Rohan")') ``` - id: with-delete name: With `delete()` code: | ```js const { data, error } = await supabase .from('countries') .delete() .filter('name', 'in', '("Mordor","The Shire")') ``` - id: with-rpc name: With `rpc()` code: | ```js // Only valid if the Postgres function returns a table type. const { data, error } = await supabase .rpc('echo_all_countries') .filter('name', 'in', '("Mordor","The Shire")') ``` - id: filter-embedded-resources name: Filter embedded resources code: | ```js const { data, error } = await supabase .from('instruments') .select('name, orchestral_sections ( name )') .filter('orchestral_sections.name', 'in', '("strings","woodwinds")') ```