Edge Functions let you run code close to users for faster responses. Calling them from the client means your app can get data or do tasks quickly and securely.
0
0
Invoking Edge Functions from client in Supabase
Introduction
You want to fetch data from your backend without exposing your database directly.
You need to run custom logic like sending emails or processing payments triggered by user actions.
You want to keep your app fast by running code near the user's location.
You want to keep sensitive operations on the server but trigger them from the app.
You want to handle user requests that require authentication and authorization.
Syntax
Supabase
const { data, error } = await supabase.functions.invoke('function-name', {
body: JSON.stringify({ key: 'value' }),
headers: { 'Content-Type': 'application/json' }
})Replace 'function-name' with your deployed Edge Function's name.
The body is optional and should be a JSON string if you send data.
Examples
Call an Edge Function named 'hello-world' without sending any data.
Supabase
const { data, error } = await supabase.functions.invoke('hello-world')Call 'add-user' function and send a username in the request body.
Supabase
const { data, error } = await supabase.functions.invoke('add-user', {
body: JSON.stringify({ username: 'alice' })
})Call 'get-profile' function with an authorization token in headers.
Supabase
const { data, error } = await supabase.functions.invoke('get-profile', {
headers: { 'Authorization': 'Bearer your-token' }
})Sample Program
This example creates a Supabase client and calls an Edge Function named 'hello-world'. It logs the response or error to the console.
Supabase
import { createClient } from '@supabase/supabase-js' const supabaseUrl = 'https://xyzcompany.supabase.co' const supabaseKey = 'public-anonymous-key' const supabase = createClient(supabaseUrl, supabaseKey) async function callEdgeFunction() { const { data, error } = await supabase.functions.invoke('hello-world') if (error) { console.error('Error calling function:', error.message) } else { console.log('Function response:', data) } } callEdgeFunction()
OutputSuccess
Important Notes
Always handle errors when calling Edge Functions to avoid app crashes.
Use JSON.stringify to send data in the request body.
Edge Functions run on the server side, so keep secrets and sensitive logic there.
Summary
Edge Functions run code near users for fast responses.
You call them from the client using supabase.functions.invoke().
Send data as JSON and handle errors properly.