Установка
SKILL.md
Supabase Webhooks & Database Events
Overview
Supabase offers four complementary event mechanisms: Database Webhooks (trigger-based HTTP calls via pg_net), supabase_functions.http_request() (call Edge Functions from triggers), Postgres LISTEN/NOTIFY (lightweight pub/sub), and Realtime postgres_changes (client-side event subscriptions). This skill covers all four patterns with production-ready code including signature verification, idempotency, and retry handling.
Prerequisites
- Supabase project (local or hosted) with
supabaseCLI installed pg_netextension enabled: Dashboard > Database > Extensions > search "pg_net" > Enable@supabase/supabase-jsv2+ installed for client-side patterns- Edge Functions deployed for webhook receiver patterns
Authentication
Both directions of a webhook are authenticated:
- Outbound (trigger → Edge Function): the trigger sends an
Authorization: Bearer <service_role_key>header. Store the key in a Postgres setting (app.settings.service_role_key) or Supabase Vault — never inline it in a committed migration. - Inbound (Edge Function receiver): verify an HMAC-SHA256 signature against a shared
WEBHOOK_SECRET(read fromDeno.env) using a constant-time comparison, and reject mismatches with401. See signature-verification.md.
Instructions
Pick the mechanism that fits the consumer: pg_net triggers for server-side HTTP fan-out, Edge Function receivers for signed processing, LISTEN/NOTIFY for in-database pub/sub, and Realtime for client UI. Write each SQL trigger to a supabase/migrations/ file and each handler to supabase/functions/<name>/index.ts, then apply and deploy with the supabase CLI.
Step 1 — Database Webhooks with pg_net and Trigger Functions
Enable pg_net, then write a trigger function that POSTs the changed row to an Edge Function. Attach it AFTER INSERT/UPDATE/DELETE. Full trigger set (conditional status-change trigger, the supabase_functions.http_request() built-in helper, and net._http_response inspection queries) is in database-webhooks.md.
CREATE EXTENSION IF NOT EXISTS pg_net WITH SCHEMA extensions;
CREATE OR REPLACE FUNCTION public.notify_order_created()
RETURNS trigger AS $$
BEGIN
PERFORM net.http_post(
url := 'https://<project-ref>.supabase.co/functions/v1/on-order-created',
headers := jsonb_build_object('Content-Type', 'application/json'),
body := jsonb_build_object('type', TG_OP, 'record', row_to_json(NEW)::jsonb)
);
RETURN NEW;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
CREATE TRIGGER on_order_created
AFTER INSERT ON public.orders
FOR EACH ROW EXECUTE FUNCTION public.notify_order_created();
Step 2 — Edge Function Webhook Receivers with Signature Verification
Write an Edge Function that reads the raw body, verifies the HMAC signature, parses the typed payload, and routes by event type. Guard against duplicate delivery with a processed_events idempotency table. The complete receiver, the idempotent-handler variant, and the idempotency table DDL are in edge-function-receivers.md.
// supabase/functions/on-order-created/index.ts
serve(async (req) => {
const rawBody = await req.text();
const secret = Deno.env.get("WEBHOOK_SECRET");
if (secret) {
const sig = req.headers.get("x-webhook-signature") ?? "";
if (!(await verifySignature(rawBody, sig, secret)))
return new Response(JSON.stringify({ error: "Invalid signature" }), { status: 401 });
}
const payload = JSON.parse(rawBody); // { type, table, record, old_record }
// route by payload.type: INSERT | UPDATE | DELETE
return new Response(JSON.stringify({ received: true }));
});
Step 3 — Postgres LISTEN/NOTIFY and Realtime as Event Source
Use pg_notify from a trigger for lightweight, non-persistent pub/sub consumed by a backend LISTEN; use Realtime postgres_changes for client-side UI subscriptions (keep NOTIFY payloads to IDs — they truncate past 8000 bytes). The backend listener, the full Realtime subscription with event routing, and the combined event-driven architecture diagram are in listen-notify-realtime.md.
const channel = supabase
.channel("orders-events")
.on("postgres_changes",
{ event: "*", schema: "public", table: "orders" },
(payload) => console.log(payload.eventType, payload.new))
.subscribe();
Output
These patterns produce:
- Database trigger functions calling Edge Functions via
pg_neton row changes - Conditional triggers that fire only when specific columns change
- Edge Function webhook receivers with HMAC signature verification
- Idempotent event processing preventing duplicate side effects
- LISTEN/NOTIFY channels for lightweight inter-service communication
- Realtime subscriptions for live client-side UI updates
- An event-driven architecture combining server and client patterns
Error Handling
| Error | Cause | Fix |
|---|---|---|
pg_net returns 404 | Edge Function not deployed or wrong URL | Run supabase functions deploy <name> and verify the URL matches |
| Webhook not firing | Trigger not attached or table not in publication | Check SELECT * FROM pg_trigger WHERE tgrelid = 'orders'::regclass; |
| Duplicate events processed | No idempotency layer | Add processed_events table with unique event_id constraint |
| Realtime not receiving | Table not added to Realtime publication | Dashboard > Database > Replication > enable the table |
net._http_response shows 401 | Invalid or missing auth header | Verify service_role_key is set in app.settings or vault |
| NOTIFY payload truncated | Payload exceeds 8000 bytes | Send only IDs in NOTIFY, fetch full record in the listener |
| Auth hook errors | Function raises exception | Check Dashboard > Logs > Auth; ensure function returns valid JSONB |
| Trigger silently fails | SECURITY DEFINER without search_path | Add SET search_path = public, extensions; to function |
Examples
- database-webhooks.md — full
pg_nettrigger set: conditional status-change trigger, thesupabase_functions.http_request()helper, andnet._http_responseinspection queries. - edge-function-receivers.md — complete signed Edge Function receiver, idempotent handler, and idempotency-table DDL.
- listen-notify-realtime.md — backend
LISTENclient, full Realtime subscription, and the combined event-driven architecture diagram. - examples.md — local webhook testing with ngrok and curl.
- signature-verification.md — Node.js HMAC signature verification.
- event-handler-pattern.md — a typed event dispatcher pattern.
Resources
- Database Webhooks — configure via Dashboard or SQL
- pg_net Extension — async HTTP from PostgreSQL
- Edge Functions — Deno-based serverless handlers
- Realtime postgres_changes — client-side subscriptions
- Auth Hooks — custom JWT claims and login events
- supabase-js Reference —
channel().on()API
Next Steps
For performance optimization of triggers and queries, see supabase-performance-tuning. For production hardening including RLS policies on webhook-accessed tables, see supabase-security-basics.
Вставить в README
Ссылка на карточку для вашего README — без картинок и счётчиков.
[DarkPlay: supabase-webhooks-events](https://darkplay.ru/ai/skills/jeremylongshore-claude-code-plugins-plus-skills-supabase-webhooks-events)
Из того же репозитория
Похожие скиллы и другие разделы каталога
Самые востребованные скиллов раздела по установкам и звёздам.
find-skillsvercel-labs · Помогает находить и устанавливать навыки агентов по запросам вроде «как сделать X»…
grill-memattpocock · Настойчивое интервью для доработки плана или дизайна.
hyperframesheygen-com · Обязательная точка входа для любых задач по видео, анимации и motion-графике в…
hyperframes-cliheygen-com · Цикл разработки HyperFrames CLI: init, add, render, preview, publish и другие команды.
agent-browservercel-labs · CLI для автоматизации браузера для ИИ-агентов: навигация по страницам, заполнение форм…
media-useheygen-com · Agent Media OS: единый навык для медиа в HyperFrames — BGM, SFX, изображения, голос, LUT.
hyperframes-registryheygen-com · Установка и подключение блоков реестра в композиции HyperFrames через add и catalog.
grill-with-docsmattpocock · Настойчивое интервью для доработки плана или дизайна, попутно создающее документацию (ADR…
improve-codebase-architecturemattpocock · Поиск в кодовой базе возможностей для углубления, визуальный HTML-отчёт о них и детальный…
tddmattpocock · Разработка через тестирование (TDD): red-green-refactor и интеграционные тесты.Соседние разделы каталога: возможно, нужный инструмент живёт там.
Database Revieweraffaan-m · Специалист PostgreSQL: оптимизация запросов, схемы, безопасность, Supabase.
ruflo-dddruvnet · Каркас Domain-Driven Design: ограниченные контексты, агрегатные корни, доменные события и…
circlebackanthropics · Интеграция с контекстом разговоров Circleback. Поиск и доступ к встречам, письмам…
mercadopagoanthropics · Полный набор инструментов интеграции Mercado Pago. Один агент направляет к четырём…
sonarqubeanthropics · Автоматическое обеспечение качества и безопасности кода SonarQube в цикле агентного…
supabaseanthropics · Интеграция Supabase MCP для работы с базой данных, аутентификации, хранилища и подписок в…
zoom-pluginanthropics · Плагин Claude для планирования, разработки и отладки интеграций Zoom через REST API, SDK…
block-no-verifywshobson · Хук PreToolUse, который не даёт ИИ-агентам использовать флаги обхода вроде --no-verify и…
zoom-pluginanthropics · Планирование, разработка и отладка интеграций Zoom через REST API, Meeting SDK, Video…
Clojure Interactive Programminggithub · Экспертный парный программист по Clojure с методологией REPL-first, архитектурным…Лучшие ИИ-инструменты для генерации видео
Подборка нейросетей для генерации и монтажа видео. Инструменты, которые превращают текст в готовые ролики, экономят часы на съемках и постпродакшне. Подходит для SMM-специалистов,
VEED.IOVeed
MootionMootion
Sora (OpenAI)OpenAI
viralpulse.appViralpulse
Viral Maker AIViral-makerЛучшие ИИ-инструменты для генерации текста и копирайтинга
Подборка нейросетей для генерации текстов и копирайтинга. Сервисы, которые помогают создавать статьи, посты и рекламные объявления с нуля или по черновику, экономя часы рутинной ра
NeuroscribeNeuroscribe
GoGPTGogpt
НейроТекстерNeuro-texter
ChatGPTOpenAI
Cosmo ScribeCosmoscribe
Memo HelperCopilot33
LibraChatLibrachatЛучшие ИИ-инструменты для генерации изображений
Подборка нейросетей для генерации изображений от фотореализма до концепт-арта. Сервисы, которые экономят часы ручной работы, создавая визуал для блогов, рекламы и дизайна за минуты
MagviMagvi
DALL-E 3OpenAI
SupaLabSupalab
Freestyling.aiFreestyling
ArtGeneration.meArtgeneration
BigjpgBigjpg
Художник от VKVK
Avato AI12ai
Virton AIVirton