The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
docs: call Edge Functions from Postgres with the secret key (#51990)
Alexis Aguilar8a78b7e5be97
diff --git a/apps/docs/content/_partials/pg_net_queued_key.mdx b/apps/docs/content/_partials/pg_net_queued_key.mdxnew file mode 100644index 00000000000..0d8f508e47e--- /dev/null+++ b/apps/docs/content/_partials/pg_net_queued_key.mdx@@ -0,0 +1,5 @@+<Admonition type="caution">++Any role that can log in to your database can read the secret key while the request waits. `pg_net` [writes the decrypted key to `net.http_request_queue`](/docs/guides/troubleshooting/database-roles-can-read-request-headers-queued-by-pg_net-ad6357) until it sends the request.++</Admonition>diff --git a/apps/docs/content/guides/database/webhooks.mdx b/apps/docs/content/guides/database/webhooks.mdxindex 37063fd01f6..9e936a2136b 100644--- a/apps/docs/content/guides/database/webhooks.mdx+++ b/apps/docs/content/guides/database/webhooks.mdx@@ -41,6 +41,66 @@ execute function "supabase_functions"."http_request"(We currently support HTTP webhooks. These can be sent as `POST` or `GET` requests with a JSON payload.+## Call an Edge Function++A webhook can call an [Edge Function](/docs/guides/functions) on each table event, and the function receives the [payload](#payload) as its request body. Call the function with your project's secret key, and accept it in the function with `auth: 'secret'` and `verify_jwt = false`. For more information, see [Service-to-service calls](/docs/guides/functions/auth#service-to-service-calls).++### From the Supabase Dashboard++1. Create a [Database Webhook](/dashboard/project/_/integrations/webhooks/overview) in the Supabase Dashboard.+1. In **Type of webhook**, select **Supabase Edge Functions**, then select your function.+1. Under **HTTP Headers**, select **Add secret key**.++The webhook saves the key in its trigger definition, so the key appears anywhere the trigger's SQL does, such as a database dump.++### From a migration++To keep the secret key out of your migration files, store it in [Supabase Vault](/docs/guides/database/vault) and read it from a trigger function.++1. In the [SQL Editor](/dashboard/project/_/sql/new), store your project URL and secret key in Vault. Run these statements once for each project, outside your migrations:++ ```sql+ select vault.create_secret('https://project-ref.supabase.co', 'project_url');+ select vault.create_secret('YOUR_SUPABASE_SECRET_KEY', 'secret_key');+ ```++1. In a migration, create a trigger function that reads both values from Vault and calls the Edge Function with [`pg_net`](/docs/guides/database/extensions/pg_net). Then attach it to the table:++ ```sql+ create function public.call_function_name()+ returns trigger+ language plpgsql+ security definer+ set search_path = ''+ as $$+ begin+ perform net.http_post(+ url := (select decrypted_secret from vault.decrypted_secrets where name = 'project_url') || '/functions/v1/function-name',+ headers := jsonb_build_object(+ 'Content-Type', 'application/json',+ 'apikey', (select decrypted_secret from vault.decrypted_secrets where name = 'secret_key')+ ),+ body := jsonb_build_object(+ 'type', tg_op,+ 'table', tg_table_name,+ 'schema', tg_table_schema,+ 'record', to_jsonb(new),+ 'old_record', null+ )+ );+ return new;+ end;+ $$;++ create trigger call_function_name+ after insert on public.my_table+ for each row execute function public.call_function_name();+ ```++ The trigger function is `security definer` because the roles that insert rows, such as `authenticated`, can't read Vault. Without it, their inserts fail with a permission error.++<$Partial path="pg_net_queued_key.mdx" />+## PayloadThe payload is automatically generated from the underlying table record:diff --git a/apps/docs/content/guides/functions/auth.mdx b/apps/docs/content/guides/functions/auth.mdxindex f502c125ad4..254d3272a79 100644--- a/apps/docs/content/guides/functions/auth.mdx+++ b/apps/docs/content/guides/functions/auth.mdx@@ -62,18 +62,29 @@ A handler that queries a shared table through `ctx.supabaseAdmin` without filter### Service-to-service calls-Cron jobs, workers, `pg_net`, and other Edge Functions make calls with a secret key on the `apikey` header rather than a user JWT. Disable `verify_jwt` and use `auth: 'secret'`. The wrapper validates the key against the secret key named `default` in your [project's API keys](/dashboard/project/_/settings/api-keys), and gives your handler `ctx.supabaseAdmin` for privileged work.+Cron jobs, workers, `pg_net`, and other Edge Functions make calls with a secret key on the `apikey` header rather than a user JWT. To accept the key:-```ts-import { withSupabase } from 'npm:@supabase/server@1'+1. In `supabase/config.toml`, disable the [`verify_jwt` check](/docs/guides/functions/auth-headers) for the function:-export default {- fetch: withSupabase({ auth: 'secret' }, async (_req, ctx) => {- // your business logic. ctx.supabaseAdmin bypasses RLS- return Response.json({ ok: true })- }),-}-```+ ```toml+ [functions.your-function]+ verify_jwt = false+ ```++1. In the function, use `auth: 'secret'`. The wrapper validates the key against the secret key named `default` in your [project's API keys](/dashboard/project/_/settings/api-keys), and gives your handler `ctx.supabaseAdmin` for privileged work:++ ```ts+ import { withSupabase } from 'npm:@supabase/server@1'++ export default {+ fetch: withSupabase({ auth: 'secret' }, async (_req, ctx) => {+ // your business logic. ctx.supabaseAdmin bypasses RLS+ return Response.json({ ok: true })+ }),+ }+ ```++To call a function from Postgres with the secret key, see [Call an Edge Function](/docs/guides/database/webhooks#call-an-edge-function) for Database Webhooks and [Scheduling Edge Functions](/docs/guides/functions/schedule-functions) for `pg_cron`.<Admonition type="note">diff --git a/apps/docs/content/guides/functions/schedule-functions.mdx b/apps/docs/content/guides/functions/schedule-functions.mdxindex 6da4d090149..5b5893477e0 100644--- a/apps/docs/content/guides/functions/schedule-functions.mdx+++ b/apps/docs/content/guides/functions/schedule-functions.mdx@@ -20,11 +20,11 @@ To access the auth token securely for your Edge Function call, we recommend stor### Invoke an Edge Function every minute-Store `project_url` and `publishable_key` in Supabase Vault:+Call the function with your secret key. Don't use your publishable key, because it's public and anyone who has it can call a function that accepts it. Store your project URL and secret key in Supabase Vault:```sqlselect vault.create_secret('https://project-ref.supabase.co', 'project_url');-select vault.create_secret('YOUR_SUPABASE_PUBLISHABLE_KEY', 'publishable_key');+select vault.create_secret('YOUR_SUPABASE_SECRET_KEY', 'secret_key');```Make a POST request to a Supabase Edge Function every minute:@@ -40,7 +40,7 @@ selecturl:= (select decrypted_secret from vault.decrypted_secrets where name = 'project_url') || '/functions/v1/function-name',headers:=jsonb_build_object('Content-type', 'application/json',- 'apikey', (select decrypted_secret from vault.decrypted_secrets where name = 'publishable_key')+ 'apikey', (select decrypted_secret from vault.decrypted_secrets where name = 'secret_key')),body:=concat('{"time": "', now(), '"}')::jsonb) as request_id;@@ -48,6 +48,10 @@ select);```+The function receives the secret key on the `apikey` header. To accept it, disable `verify_jwt` and use `auth: 'secret'`. For more information, see [Service-to-service calls](/docs/guides/functions/auth#service-to-service-calls).++<$Partial path="pg_net_queued_key.mdx" />+## Resources- [`pg_net` extension](/docs/guides/database/extensions/pg_net)