Updated on November 4, 2026
You can run the whole WhatsApp Business API webhook on Supabase: an Edge Function (Deno) answers Meta’s verification request, validates the X-Hub-Signature-256 signature, stores messages and statuses in Postgres and replies to the customer through the API. The one mandatory tweak is turning off JWT verification for that function, because Meta does not send a Supabase token.
This guide gives you the table SQL, the full function code, the deploy commands and the Supabase limits worth watching.
Why Supabase for a WhatsApp webhook
A WhatsApp webhook needs three things: a public HTTPS URL, a fast HTTP 200 response and somewhere to store what arrives. Supabase gives you all three in one project. The Edge Function is the URL, Postgres stores messages and statuses, and the Supabase dashboard already lets you browse the data without another tool.
It is the same reasoning as a serverless webhook on Cloudflare Workers, Lambda or Vercel, with the bonus that the database sits right next to the function. If you are new to the event format, start with the WhatsApp API webhooks guide.
What you need first
- A Supabase project and the CLI logged in (
supabase loginandsupabase link --project-ref YOUR_PROJECT). - A number on the official WhatsApp API and its
phone_number_id. - Your Meta app’s app secret (to validate the signature) and a verify token, any string you make up.
- A token to send messages: the Meta access token or, if you use Vectalk, an instance token.
Want to try it while you read? Create a Vectalk account and send your first message through the official API. Create free account →
Step 1: create the tables
Two tables cover most cases: one for messages (inbound and outbound) and one for delivery statuses. The wamid, the ID Meta assigns to each message, is a unique key, which makes writes idempotent: if Meta resends the same event, the database ignores it.
create table public.wa_messages (
id bigint generated always as identity primary key,
wamid text unique not null,
phone_number_id text not null,
contact_wa_id text not null,
contact_name text,
direction text not null check (direction in ('in', 'out')),
type text not null,
body text,
raw jsonb not null,
sent_at timestamptz not null default now()
);
create table public.wa_statuses (
id bigint generated always as identity primary key,
wamid text not null,
status text not null,
recipient_wa_id text,
errors jsonb,
raw jsonb not null,
status_at timestamptz not null,
unique (wamid, status)
);
create index on public.wa_messages (contact_wa_id, sent_at desc);
alter table public.wa_messages enable row level security;
alter table public.wa_statuses enable row level security;
With RLS on and no policies, only the secret key (used by the function) can read and write. If your front end will query these tables, add specific policies for signed-in users. To go further (export, retention, deletion), see how to save WhatsApp conversation history.
Step 2: create the function and turn off JWT
supabase functions new whatsapp-webhook
By default, every Edge Function requires a valid Supabase JWT in the Authorization header. Meta does not send one, so the call would die with a 401. The function configuration docs show how to disable the check for this function only, in supabase/config.toml:
[functions.whatsapp-webhook]
verify_jwt = false
Supabase itself warns that this lets anyone invoke the function. That is why the signature check in step 3 is not optional: it replaces the JWT as proof that the event came from Meta.
Step 3: the Edge Function code
The function does four things: answers the verification GET, validates the POST signature over the raw body, returns 200 and processes the event in the background with EdgeRuntime.waitUntil, described in background tasks.
// supabase/functions/whatsapp-webhook/index.ts
import { createClient } from "npm:@supabase/supabase-js@2";
const VERIFY_TOKEN = Deno.env.get("WA_VERIFY_TOKEN")!;
const APP_SECRET = Deno.env.get("META_APP_SECRET")!;
const SEND_URL = Deno.env.get("WA_SEND_URL")!; // Meta or Vectalk
const SEND_TOKEN = Deno.env.get("WA_SEND_TOKEN")!;
const secretKeys = JSON.parse(Deno.env.get("SUPABASE_SECRET_KEYS") ?? "{}");
const db = createClient(
Deno.env.get("SUPABASE_URL")!,
secretKeys["default"] ?? Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!,
);
async function validSignature(raw: string, header: string | null) {
if (!header?.startsWith("sha256=")) return false;
const key = await crypto.subtle.importKey(
"raw", new TextEncoder().encode(APP_SECRET),
{ name: "HMAC", hash: "SHA-256" }, false, ["sign"],
);
const sig = await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(raw));
const hex = [...new Uint8Array(sig)].map((b) => b.toString(16).padStart(2, "0")).join("");
const got = header.slice(7);
if (got.length !== hex.length) return false;
let diff = 0;
for (let i = 0; i < hex.length; i++) diff |= hex.charCodeAt(i) ^ got.charCodeAt(i);
return diff === 0;
}
async function reply(phoneNumberId: string, to: string, text: string) {
const res = await fetch(SEND_URL.replace("{PHONE_NUMBER_ID}", phoneNumberId), {
method: "POST",
headers: { Authorization: `Bearer ${SEND_TOKEN}`, "Content-Type": "application/json" },
body: JSON.stringify({ messaging_product: "whatsapp", to, type: "text", text: { body: text } }),
});
const data = await res.json();
const wamid = data?.messages?.[0]?.id;
if (wamid) {
await db.from("wa_messages").insert({
wamid, phone_number_id: phoneNumberId, contact_wa_id: to,
direction: "out", type: "text", body: text, raw: data,
});
}
}
async function process(payload: any) {
for (const entry of payload.entry ?? []) {
for (const change of entry.changes ?? []) {
if (change.field !== "messages") continue;
const v = change.value;
const phoneNumberId = v.metadata?.phone_number_id;
const names = Object.fromEntries((v.contacts ?? []).map((c: any) => [c.wa_id, c.profile?.name]));
for (const m of v.messages ?? []) {
const { data: novas, error } = await db.from("wa_messages").upsert({
wamid: m.id, phone_number_id: phoneNumberId, contact_wa_id: m.from,
contact_name: names[m.from] ?? null, direction: "in", type: m.type,
body: m.text?.body ?? m.interactive?.button_reply?.title ?? null,
raw: m, sent_at: new Date(Number(m.timestamp) * 1000).toISOString(),
}, { onConflict: "wamid", ignoreDuplicates: true }).select("id");
if (error) console.error(error);
// reply only if the row is new (a Meta retry does not trigger a second reply)
if (m.type === "text" && novas?.length) {
await reply(phoneNumberId, m.from, "We got your message. We'll reply shortly!");
}
}
for (const s of v.statuses ?? []) {
await db.from("wa_statuses").upsert({
wamid: s.id, status: s.status, recipient_wa_id: s.recipient_id,
errors: s.errors ?? null, raw: s,
status_at: new Date(Number(s.timestamp) * 1000).toISOString(),
}, { onConflict: "wamid,status", ignoreDuplicates: true });
}
}
}
}
Deno.serve(async (req) => {
const url = new URL(req.url);
if (req.method === "GET") {
const ok = url.searchParams.get("hub.mode") === "subscribe" &&
url.searchParams.get("hub.verify_token") === VERIFY_TOKEN;
return ok
? new Response(url.searchParams.get("hub.challenge"), { status: 200 })
: new Response("forbidden", { status: 403 });
}
if (req.method !== "POST") return new Response("method not allowed", { status: 405 });
const raw = await req.text(); // raw body: the signature is computed over it
if (!(await validSignature(raw, req.headers.get("x-hub-signature-256")))) {
return new Response("invalid signature", { status: 401 });
}
EdgeRuntime.waitUntil(process(JSON.parse(raw)).catch(console.error));
return new Response("ok", { status: 200 });
});
Common pitfalls:
- Raw body. The signature is an HMAC-SHA256 of the payload using the app secret, per the webhook endpoint docs. Read it with
req.text()and only thenJSON.parse; re-serializing the JSON changes the bytes and the signature won’t match. Other languages are covered in how to validate the webhook signature. - Database key. The function uses the secret key Supabase injects. According to the secrets page,
SUPABASE_URLandSUPABASE_SECRET_KEYS(a JSON object with adefaultkey) are already in the environment;SUPABASE_SERVICE_ROLE_KEYis still available as a legacy key. - Auto-reply to every text. The example replies to any inbound text just to show the flow. In production, swap in your own rule (business hours, first message of the day, hand-off to a bot).
Step 4: secrets and deploy
Custom secret names cannot start with SUPABASE_, which is reserved. Set yours and deploy:
supabase secrets set WA_VERIFY_TOKEN=a-string-you-made-up
supabase secrets set META_APP_SECRET=your_app_secret
supabase secrets set WA_SEND_TOKEN=your_token
supabase secrets set WA_SEND_URL="https://graph.facebook.com/vXX.X/{PHONE_NUMBER_ID}/messages"
supabase functions deploy whatsapp-webhook
Replace vXX.X with the Graph API version your app uses. The function’s public URL looks like https://YOUR_PROJECT.supabase.co/functions/v1/whatsapp-webhook.
Step 5: plug the URL into Meta
In your app dashboard, under WhatsApp > Configuration, paste the function URL as the callback URL along with the same verify token. Meta sends a GET with hub.mode, hub.verify_token and hub.challenge; the function returns hub.challenge with a 200 and verification passes. Then subscribe to the messages field. Send a message to the number and check for new rows in wa_messages.
If nothing shows up, check the function logs in the Supabase dashboard and follow the webhook-not-working checklist.
Supabase limits that matter for a webhook
| Limit | Value | What it means here |
|---|---|---|
| Wall clock time | 150 s on Free, 400 s on paid plans | Also caps the waitUntil task |
| CPU time per request | 2 s | Async I/O (database, fetch) doesn’t count; HMAC and JSON are cheap |
| Memory | 256 MB | Don’t download large media inside the function |
| Request idle timeout | 150 s | Irrelevant if you return 200 before processing |
Values from the limits page. Meta retries unacknowledged events for up to 7 days and may batch up to 1,000 updates in a single POST. That is why the upsert uses ignoreDuplicates and .select(): a retry doesn’t create a duplicate row, and the auto-reply only fires when the row was just inserted.
When volume grows or processing gets heavy (AI, transcription, CRM), replace waitUntil with a queue: store the payload in a table and process it with a worker. The full design is in integration architecture with queues, retries and idempotency.
How to do it with Vectalk
Vectalk is a proxy for the official API: according to the Vectalk webhook docs, the Hub forwards the same payload it receives from Meta to your registered URLs, so the tables and process() above work unchanged. Register the function URL with POST https://apis.vectalk.com.br/api/webhooks (fields instance_id, url and name) and return 200 within 20 seconds. To send, set WA_SEND_URL=https://apis.vectalk.com.br/api/messages and use an instance token as WA_SEND_TOKEN; the token resolves the phone_number_id.
Vectalk’s docs don’t describe a signature header on forwarded events. In that case, replace the X-Hub-Signature-256 check with your own secret in the registered URL (for example, ?key=... compared against a function secret) and confirm with support what the Hub sends. To get started, create your account.
Frequently asked questions
Why does my Edge Function return 401 to Meta?
It’s almost always the JWT. Without verify_jwt = false in config.toml, Supabase requires a token in the Authorization header and blocks the call before your code runs.
Can I use the anon key instead of the secret key?
With RLS on and no policies, the anon key can’t write anything. The secret key stays server-side (inside the function) and must never reach the front end.
Can the Edge Function receive media?
Yes, but the webhook only carries the media ID. You have to download it afterwards with your token and store it in Supabase Storage, ideally outside the webhook’s critical path. See how to download media customers send.
Can one function serve several numbers?
Yes. Each event’s metadata.phone_number_id tells you which number received the message, and the phone_number_id column stores it. For multiple customers, see multi-tenant SaaS on the WhatsApp API.
Official sources checked on November 4, 2026: Meta: create a webhook endpoint, Meta: webhooks overview, Supabase: function configuration, Supabase: secrets, Supabase: background tasks, Supabase: deploy, Supabase: limits, Vectalk: webhooks, Vectalk: authentication.
Try the official WhatsApp API today
Create your account, generate a token and send your first message with the quick-start guide. Same payloads and webhooks as Meta's Cloud API.
