Vojtech Pavlovsky

Trigger Private Supabase Cloud Function From Database

Cloud Functions in Supabase are by default protected by JWT and can be called by anyone. Sometimes you want to restrict these functions to be accessible only from within context of your Supabase project. For example, you might want to send a push notification when new entry is inserted into your database. This can be done quite easily in Firebase/Firestore but for Supabase it's a bit more complicated.

Supabase Service Key

Instead, you can use Supabase Service Key (available in your project settings) to verify that the request has been made by you or your internal Supabase services.

Following example uses simple Deno function which requires a Service Key to run. You can get this key from environment variables. Fortunately, SUPABASE_SERVICE_ROLE_KEY is automatically available.

functions/hello-world/index.ts
1import { serve } from "https://deno.land/std@0.168.0/http/server.ts";
2import { createClient } from "https://esm.sh/@supabase/supabase-js@2";
3
4// Supabase Service Key is available in env variables by default.
5const serviceKey = Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!;
6
7const supabaseUrl = Deno.env.get("SUPABASE_URL")!;
8
9serve(async (req) => {
10 // Verify that the request has been made by Supabase.
11 if (req.headers.get("Authorization") !== `Bearer ${serviceKey}`) {
12 return new Response("Unauthorized", { status: 401 });
13 }
14
15 // Create admin Supabase client.
16 const supabase = createClient(supabaseUrl, serviceKey);
17
18 // ... your code here ...
19});

To list all the environment variables available run the following command in your CLI.

1$ supabase secrets list

Database Webhooks

Now, assuming that your function is deployed and protected behind Supabase Service Key, you can create a database trigger using Supabase Webhooks.

In Database > Webhooks > Create a new webhook open the following dialog and select your table and event type (insert, update, or delete). In Webhook Configuration then select Supabase Edge Functions and pick your function from the list in Edge Functions.

Supabase Database Webhooks

Finally, select Add a new header and choose Add auth header with service key. Your Service Key will be automatically added to the request as Authorization header which you verify in your function.