Copied.
Using the Supabase SDK
Scenarios
In this section, you can learn how to use the Supabase SDK with a frontend scaffold or different API keys.
Using the Supabase SDK with a Frontend Scaffold
Prerequisites
- A Supabase AI application has been created and is running normally.
- To access the application over the public network, bind an EIP by referring to Binding and Unbinding a DNAT Gateway Address.
- The dependencies and software of the framework selected for your project have been installed and correctly configured.
For example, if you select React, ensure that Node.js is installed and npm is available.
Step 1: Obtain Supabase Environment Variables (Access Address and API Key)
- Log in to the RDS console.
- Click
in the upper left corner and select a region. - In the navigation pane, choose AI App Dev Platform. In the application list, locate the target Supabase application.
- Click Log in to Supabase in the Operation column.
- In the dialog box that is displayed, click the corresponding login method based on the network environment to access the Supabase Dashboard. Figure 1 Supabase Dashboard
- The username is supabase.
- The login password is set by the user during application creation.
- In the upper left corner of the page, click Connect. The project connection configuration page is displayed.
- Select App Frameworks, select the framework of your project application from the drop-down list, and view its .env environment variable configuration. Figure 2 RDS Supabase application environment variables (React used as the app framework)
Obtain the application access address and anon API key from the environment variable configuration. For details, see Table 1.
Step 2: Interconnect the Framework with the SDK (Quick Start)
React is used as an example. You need to create a scaffold project locally and start it to experience a complete development practice without backends.
- Based on your project's technology stack, click the icon to access the corresponding framework interconnection guide on the official Supabase SDK framework website. This will help you fully understand the end-to-end operation process and coding practices.
This page provides simple scaffold demo projects to help you quickly get started and experience the complete interconnection, usage, and startup process.
Figure 3 Shortcuts for interconnection with the Supabase SDK
- Create an initialization project for your application using the template provided in the guide.
- Install the Supabase client SDK library.
- Modify the Supabase environment variables.
Create the environment variable file .env.local. Replace the content with that obtained in Step 1: Obtain Supabase Environment Variables (Access Address and API Key).
VITE_SUPABASE_URL={Supabase-application-access-address} VITE_SUPABASE_PUBLISHABLE_KEY={Supabase-API-key} - Interconnect the project code with the SDK and use related tools and methods. In the project, src/lib/supabaseClient.js corresponds to a code snippet for creating a Supabase client. The code snippet is as follows:
import { createClient } from '@supabase/supabase-js' const supabaseUrl = import.meta.env.VITE_SUPABASE_URL const supabasePublishableKey = import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY export const supabase = createClient(supabaseUrl, supabasePublishableKey)After creating a Supabase client, you can use the client to call the SDK tool suite and all methods, for example, querying database data.
Example: Query all rows in the instruments table.
const { data, error } = await supabase.from('instruments').select() - Create related database table data in the SQL Editor view of the Supabase Dashboard and complete other configuration operations by referring to the configuration section on the official website.
- Add the project code content and complete frontend coding by referring to the coding section on the official website.
- After the project is started, enter http://localhost:5173 in the address box of a browser to view all records in the instruments table.
npm run dev
Using the Supabase SDK with Different API Keys
In the examples below, you can learn how to use the client-side JavaScript SDK or server-side JavaScript SDK, and how to call the REST API from native JavaScript, all based on API keys.
Prerequisites
- You have created a Supabase AI application, enabled public network access as needed, and bound an EIP and access port based on the network environment.
- You have obtained the API keys of the application, including a publishable key, a secret key, an anon key, and a service role key.
- You have learned about the Supabase API calling methods and API list.
- The .env file is configured on the client, and the API key and user information are configured in the environment variables. This example only shows the minimum configuration. Do not store passwords in plaintext in the production environment.
Example:
SUPABASE_URL=http://xx:xx:xx:xx:8443 # New API keys SUPABASE_PUBLISHABLE_KEY=sb_publishable_xxxx_xx SUPABASE_SECRET_KEY=sb_secret_xxxx_xx # (Optional) Outdated API keys ANON_KEY=********** SERVICE_ROLE_KEY=********** # User information TEST_USER_EMAIL=xxxxx TEST_USER_PASSWORD=xxxxx
Create the tables required in the example and grant the required permissions to them.-- ============================================================ -- 1. Create tables. -- ============================================================ -- Product table CREATE TABLE products ( id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY, name TEXT NOT NULL, category TEXT, description TEXT, created_at TIMESTAMPTZ DEFAULT now(), updated_at TIMESTAMPTZ DEFAULT now() ); -- Product pricing table CREATE TABLE product_pricings ( id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY, product_id BIGINT NOT NULL REFERENCES products(id) ON DELETE CASCADE, tier TEXT NOT NULL, price NUMERIC(10,2) NOT NULL, unit TEXT DEFAULT 'USD/month', effective_from DATE DEFAULT current_date, created_at TIMESTAMPTZ DEFAULT now() ); -- ============================================================ -- 2. Enable RLS (Realtime PostgreSQL changes depend on RLS for visibility). -- ============================================================ ALTER TABLE products ENABLE ROW LEVEL SECURITY; ALTER TABLE product_pricings ENABLE ROW LEVEL SECURITY; -- ============================================================ -- 3. RLS policy -- ============================================================ -- anon read-only (recommended for the production environment) CREATE POLICY "anon_select_products" ON public.products FOR SELECT TO anon USING (true); CREATE POLICY "anon_select_product_pricings" ON public.product_pricings FOR SELECT TO anon USING (true); -- anon full CRUD (for development/testing, enabled after being uncommented) -- CREATE POLICY "anon_insert_products" ON public.products FOR INSERT TO anon WITH CHECK (true); -- CREATE POLICY "anon_insert_product_pricings" ON public.product_pricings FOR INSERT TO anon WITH CHECK (true); -- CREATE POLICY "anon_update_products" ON public.products FOR UPDATE TO anon USING (true) WITH CHECK (true); -- CREATE POLICY "anon_update_product_pricings" ON public.product_pricings FOR UPDATE TO anon USING (true) WITH CHECK (true); -- CREATE POLICY "anon_delete_products" ON public.products FOR DELETE TO anon USING (true); -- CREATE POLICY "anon_delete_product_pricings" ON public.product_pricings FOR DELETE TO anon USING (true); -- authenticated: Addition, deletion, and modification are allowed. CREATE POLICY "authenticated_select_products" ON public.products FOR SELECT TO authenticated USING (true); CREATE POLICY "authenticated_select_product_pricings" ON public.product_pricings FOR SELECT TO authenticated USING (true); CREATE POLICY "authenticated_insert_products" ON public.products FOR INSERT TO authenticated WITH CHECK (true); CREATE POLICY "authenticated_insert_product_pricings" ON public.product_pricings FOR INSERT TO authenticated WITH CHECK (true); CREATE POLICY "authenticated_update_products" ON public.products FOR UPDATE TO authenticated USING (true) WITH CHECK (true); CREATE POLICY "authenticated_update_product_pricings" ON public.product_pricings FOR UPDATE TO authenticated USING (true) WITH CHECK (true); CREATE POLICY "authenticated_delete_products" ON public.products FOR DELETE TO authenticated USING (true); CREATE POLICY "authenticated_delete_product_pricings" ON public.product_pricings FOR DELETE TO authenticated USING (true); -- service_role does not require a policy and bypasses RLS by default. -- ============================================================ -- 4. Table-level permissions (RLS performs row-level filtering, and GRANT is a table-level gate. Both are indispensable.) -- ============================================================ GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE public.products TO anon; GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE public.product_pricings TO anon; GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE public.products TO authenticated; GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE public.product_pricings TO authenticated; GRANT ALL ON TABLE product_pricings TO service_role; GRANT ALL ON ALL TABLES IN SCHEMA public TO service_role; -- ============================================================ -- 5. Realtime: A table is added to an existing publication. -- ============================================================ ALTER PUBLICATION supabase_realtime ADD TABLE public.products; ALTER PUBLICATION supabase_realtime ADD TABLE public.product_pricings; -- ============================================================ -- 6. Sample data -- ============================================================ INSERT INTO products (name, category, description) VALUES ('Cloud storage service', 'Software service', 'Enterprise-level object storage service, secure and reliable'), ('GPU cloud server', 'Hardware', 'High-performance GPU compute instances, suitable for AI training and inference'), ('API gateway', 'Software service', 'Unified API entry management, supporting rate limiting, authentication, and monitoring'), INSERT INTO product_pricings (product_id, tier, price, unit) VALUES (1, 'Basic', 99.00, 'USD/month'), (1, 'Professional', 299.00, 'USD/month'), (1, 'Enterprise', 899.00, 'USD/month'), (2, 'Standard', 1280.00, 'USD/month'), (2, 'Enhanced', 3580.00, 'USD/month'), (2, 'Premium', 8990.00, 'USD/month'), (3, 'Starter', 49.00, 'USD/month'), (3, 'Professional', 199.00, 'USD/month'), -- Refresh the PostgREST schema cache. NOTIFY pgrst, 'reload schema';
Examples of Using a Client-side JavaScript SDK with an API Key (Publishable Key)
- Scenario 1: Login authentication is not required.
import "dotenv/config"; import { createClient } from "@supabase/supabase-js"; // Create a client. const supabase = createClient( process.env.SUPABASE_URL, process.env.SUPABASE_PUBLISHABLE_KEY ); // Direct query without login const { data, error } = await supabase .from("product_pricings") .select("*") .limit(10);The RLS policy must be enabled for the anon role for the table to be accessed. Otherwise, data cannot be queried.
- Scenario 2: Login authentication is required.
import "dotenv/config"; import { createClient } from "@supabase/supabase-js"; // Create a client. const supabase = createClient( process.env.SUPABASE_URL, process.env.SUPABASE_PUBLISHABLE_KEY ); //Login const { data: loginData, error: loginError } = await supabase.auth.signInWithPassword({ email: process.env.TEST_USER_EMAIL, password: process.env.TEST_USER_PASSWORD, }); //Query after login. Use the RLS of the authenticated role. const { data, error } = await supabase .from("product_pricings") .select("*") .limit(10);
Examples of Using a Client-side JavaScript SDK with an API Key (Anon Key)
- Scenario 1: Login authentication is not required.
import "dotenv/config"; import { createClient } from "@supabase/supabase-js"; // Create a client. const supabase = createClient( process.env.SUPABASE_URL, process.env.ANON_KEY ); // Direct query without login const { data, error } = await supabase .from("product_pricings") .select("*") .limit(10);The RLS policy must be enabled for the anon role for the table to be accessed. Otherwise, data cannot be queried.
- Scenario 2: Login authentication is required.
import "dotenv/config"; import { createClient } from "@supabase/supabase-js"; // Create a client. const supabase = createClient( process.env.SUPABASE_URL, process.env.ANON_KEY ); // Login const { data: loginData, error: loginError } = await supabase.auth.signInWithPassword({ email: process.env.TEST_USER_EMAIL, password: process.env.TEST_USER_PASSWORD, }); //Query after login. Use the RLS of the authenticated role. const { data, error } = await supabase .from("product_pricings") .select("*") .limit(10);
Examples of Using a Server-side JavaScript SDK with an API Key (Secret Key or Service Role Key)
- Scenario 1: The server uses a secret key.
import "dotenv/config"; import { createClient } from "@supabase/supabase-js"; // Create a client. const supabase = createClient( process.env.SUPABASE_URL, process.env.SUPABASE_SECRET_KEY ); // Login is not required because all RLS policies are bypassed and full database permissions are granted. const { data, error } = await supabase .from("product_pricings") .select("*"); - Scenario 2: The server uses a service role key.
import "dotenv/config"; import { createClient } from "@supabase/supabase-js"; // Create a client. const supabase = createClient( process.env.SUPABASE_URL, process.env.SERVICE_ROLE_KEY ); // Login is not required because all RLS policies are bypassed and full database permissions are granted. const { data, error } = await supabase .from("product_pricings") .select("*");
The secret key or service role key cannot be exposed to the frontend and can only be used by server-side developers or administrators.
Examples of Calling a REST API from Native JavaScript with an API Key (Publishable Key)
- Scenario 1: Login authentication is not required.
curl -X GET "https://http://xx:xx:xx:xx:8443/rest/v1/product_pricings?select=*" \ -H "apikey: sb_publishable_xxxx_xx" \ -H "Authorization: Bearer sb_publishable_xxxx_xx"
- Scenario 2: Login authentication is required.
User login (obtaining the JWT):
curl -X POST "https://http://xx:xx:xx:xx:8443/auth/v1/token?grant_type=password" \ -H "apikey: sb_publishable_xxxx_xx" \ -H "Content-Type: application/json" \ -d '{"email": "user@example.com", "password": "your-password"}'Use the user JWT to request data:
curl -X GET "https://http://xx:xx:xx:xx:8443/rest/v1/product_pricings?select=*" \ -H "apikey: sb_publishable_xxxx_xx" \ -H "Authorization: Bearer <JWT-obtained-after-user-login>"
Examples of Calling a REST API from Native JavaScript with an API Key (Anon Key)
- Scenario 1: Login authentication is not required.
curl -X GET "https://http://xx:xx:xx:xx:8443/rest/v1/product_pricings?select=*" \ -H "apikey: **********" \ -H "Authorization: Bearer **********"
- Scenario 2: Login authentication is required.
User login (obtaining the JWT):
curl -X POST "https://http://xx:xx:xx:xx:8443/auth/v1/token?grant_type=password" \ -H "apikey: **********" \ -H "Content-Type: application/json" \ -d '{"email": "user@example.com", "password": "your-password"}'Use the user JWT to request data:
curl -X GET "https://http://xx:xx:xx:xx:8443/rest/v1/product_pricings?select=*" \ -H "apikey: **********" \ -H "Authorization: Bearer <JWT-obtained-after-user-login>"
What is your overall rating for this page?
Thank you very much for your feedback. We will continue working to improve the documentation.See the reply and handling status in My Cloud VOC.
For any further questions, feel free to contact us through the chatbot.
Chatbot