Event-Driven Email: The Supabase Postgres to Edge Pipeline
In Supabase architectures, client applications frequently write records directly to PostgreSQL via Row Level Security (RLS). Trying to invoke email APIs from the frontend client exposes sending secrets and fails if the user closes their browser prematurely.
The event-driven pattern uses Supabase Database Webhooks. When a row is inserted into public.orders, auth.users, or public.invoices, Postgres fires an asynchronous HTTP webhook to a Supabase Deno Edge Function, which securely authenticates and dispatches the email via SadaSend.
1. Supabase Edge Function (supabase/functions/send-order-email/index.ts)
Here is the Edge Function receiving the Postgres webhook payload, validating the database event, and routing the transactional receipt.
import "jsr:@supabase/functions-js/edge-runtime.d.ts";
interface OrderWebhookPayload {
type: 'INSERT';
table: 'orders';
record: {
id: string;
customer_email: string;
customer_name: string;
total_cents: number;
created_at: string;
};
}
Deno.serve(async (req: Request) => {
if (req.method !== 'POST') {
return new Response('Method Not Allowed', { status: 405 });
}
const payload: OrderWebhookPayload = await req.json();
const { id, customer_email, customer_name, total_cents } = payload.record;
const apiKey = Deno.env.get('SADASEND_API_KEY');
if (!apiKey) {
return new Response('Missing SADASEND_API_KEY', { status: 500 });
}
const res = await fetch('https://api.sadasend.com/emails', {
method: 'POST',
headers: {
Authorization: `Bearer ${apiKey}`,
'Content-Type': 'application/json',
'Idempotency-Key': `supabase-order-${id}`,
},
body: JSON.stringify({
to: customer_email,
subject: `Order Confirmation #${id.slice(0, 8)}`,
text: `Hi ${customer_name},\n\nThank you for your order of $${(total_cents / 100).toFixed(2)}. We are processing it now!\n\nOrder ID: ${id}`,
}),
});
const data = await res.json();
return new Response(JSON.stringify(data), {
status: res.status,
headers: { 'Content-Type': 'application/json' },
});
});2. Configuring Database Webhooks in Supabase Dashboard
- Open your Supabase project and navigate to Database → Webhooks.
- Click "Create a new hook", name it "on-order-created", and select Table: "orders".
- Check the "INSERT" event checkbox.
- Set Webhook Type to "Supabase Edge Functions" and select "send-order-email".
- Save the webhook. Every newly inserted order row now triggers an automatic receipt.
Building AI agents that send email?
Scoped API keys, per-key recipient allowlists, approval mode and a hosted MCP server with ten tools — on the free plan, without a card.