This guide builds one Supabase Edge Function that receives WhatsApp webhooks on a Dualhook connection. The function was tested on 30 November 2026 by running it locally under Deno 2.9.6 with @supabase/server 1.9.2, with local stand-ins for EdgeRuntime.waitUntil, the database API and the Runtime API. It was not deployed to a Supabase project.
The guide applies to any Supabase project, including one you connected to Lovable: Lovable deploys edge functions to your own Supabase project and stores their secrets there. On Lovable's built-in backend, Lovable writes and deploys edge functions from the project chat, so the CLI and Dashboard steps on this page do not apply there.
Prerequisites
- A Supabase project, and either the Supabase CLI or access to the project's Dashboard
- The project's
defaultpublishable and secret API keys, under Settings > API Keys. An older project with only the legacyanonandservice_rolekeys shows a Create new API keys button there; creating them leaves the legacy keys working - A Dualhook connection in progress or active. Dualhook asks for your webhook URL and verify token before Meta's signup opens, so deploy the function first
- A verify token you choose, at least 16 characters, used only for the GET handshake
- A per-connection Dualhook
dh_live_...key and yourPHONE_NUMBER_IDfor outbound runtime sends - Your
WABA_IDfor payload-side validation
No
META_APP_SECRET? In the Embedded Signup flowX-Hub-Signature-256is signed by Dualhook's Meta app and isn't customer-verifiable: validate inbound webhook payload shape instead. These checks do not prove the sender is Meta, so treat the URL as a secret. See Messaging Webhook → Inbound Webhook POST Validation.
Architecture Overview
With Dualhook, Meta sends message-path webhooks directly to your function URL. Dualhook stays out of the message content path and focuses on setup, monitoring, and management events.
Meta (messages, statuses, errors; Coexistence echoes, history, contacts)
→ https://<project-ref>.supabase.co/functions/v1/whatsapp-webhook/<secret>
→ verification, inbound payload validation, 200
→ dedupe and your logic in a background task
→ optional send through api.dualhook.com
Dualhook
→ management events to the same URL, health visibility, template operations
The function becomes part of your message-processing boundary. Supabase does not log request or response bodies, but anything your code prints with console.log or stores in a table stays in your project, even though Dualhook itself does not store it. See Compliance & Data Retention and Architecture & Security for the privacy split.
Create the Function
With the Supabase CLI, in your project folder (run supabase init first if it has no supabase folder):
supabase functions new whatsapp-webhook
This creates supabase/functions/whatsapp-webhook/index.ts. Replace its contents with the function code, add the setting from Turn Off JWT Verification, then link the project and deploy:
supabase login
supabase link --project-ref <project-ref>
supabase functions deploy whatsapp-webhook
supabase functions deploy and supabase secrets set ask for confirmation. In a script or from a coding agent, add --yes. Deploying does not need Docker, because the CLI falls back to API-based deployment. Serving the function locally with supabase functions serve does need Docker.
Create the dedupe table at the same time, before you connect the number.
Without the CLI, open Edge Functions in the Supabase Dashboard, click Deploy a new function, choose Via Editor, paste the code and click Deploy function. The function's name is part of its URL, so name it whatsapp-webhook. The Dashboard editor has no version control, so keep a copy of the code.
The function answers at https://<project-ref>.supabase.co/functions/v1/whatsapp-webhook, and Supabase routes paths below the function name to the same function. The webhook URL you give Dualhook is that address plus one secret segment (see Keep the URL unguessable):
https://<project-ref>.supabase.co/functions/v1/whatsapp-webhook/<WEBHOOK_PATH_SECRET>
The Function Code
One file, supabase/functions/whatsapp-webhook/index.ts. The sections after it explain each part.
// supabase/functions/whatsapp-webhook/index.ts
import { type SupabaseContext, withSupabase } from 'npm:@supabase/server@1'
// Provided by the Supabase Edge Runtime. Keeps the worker alive after the response.
declare const EdgeRuntime: { waitUntil(promise: Promise<unknown>): void }
type Db = SupabaseContext['supabaseAdmin']
// deno-lint-ignore no-explicit-any
type Json = Record<string, any>
// Fields Meta sends straight to this URL. All four carry value.metadata.phone_number_id.
const MESSAGE_PATH_FIELDS = new Set([
'messages',
'smb_message_echoes',
'history',
'smb_app_state_sync',
])
export default {
fetch: withSupabase({ auth: 'none', cors: 'disabled' }, async (req, ctx) => {
const url = new URL(req.url)
// The last path segment is the secret part of the URL.
const pathSecret = Deno.env.get('WEBHOOK_PATH_SECRET')
if (!pathSecret) return notConfigured('WEBHOOK_PATH_SECRET')
if (url.pathname.split('/').pop() !== pathSecret) {
return new Response('Not found', { status: 404 })
}
// Meta's verification handshake.
if (req.method === 'GET') {
const verifyToken = Deno.env.get('WHATSAPP_VERIFY_TOKEN')
if (!verifyToken) return notConfigured('WHATSAPP_VERIFY_TOKEN')
const query = url.searchParams
if (query.get('hub.mode') === 'subscribe' && query.get('hub.verify_token') === verifyToken) {
return new Response(query.get('hub.challenge') ?? '', {
status: 200,
headers: { 'Content-Type': 'text/plain' },
})
}
return new Response('Forbidden', { status: 403 })
}
if (req.method !== 'POST') {
return new Response('Method not allowed', { status: 405, headers: { Allow: 'GET, POST' } })
}
// Until both IDs are set, answer 503 so Meta delivers again later.
const wabaId = Deno.env.get('WHATSAPP_WABA_ID')
const phoneNumberId = Deno.env.get('WHATSAPP_PHONE_NUMBER_ID')
if (!wabaId || !phoneNumberId) {
return notConfigured('WHATSAPP_WABA_ID', 'WHATSAPP_PHONE_NUMBER_ID')
}
const payload: Json | null = await req.json().catch(() => null)
if (!isExpectedPayload(payload, wabaId, phoneNumberId)) {
return new Response('Unauthorized', { status: 401 })
}
// The sample event from Dualhook's Test endpoint carries no message.
if (req.headers.get('X-Dualhook-Event') === 'test_ping') {
console.log('Dualhook Test endpoint ping')
return new Response('OK', { status: 200 })
}
// Answer now, work after the response.
EdgeRuntime.waitUntil(
processPayload(payload, ctx.supabaseAdmin).catch((error) => {
console.error('webhook processing failed', error)
}),
)
return new Response('OK', { status: 200 })
}),
}
function notConfigured(...names: string[]): Response {
const missing = names.filter((name) => !Deno.env.get(name))
console.error('Not configured. Missing secrets:', missing.join(', '))
return new Response('Not configured', { status: 503 })
}
// Envelope, WABA ID, then the phone number ID on the fields that carry one.
function isExpectedPayload(
payload: Json | null,
wabaId: string,
phoneNumberId: string,
): payload is Json {
if (payload?.object !== 'whatsapp_business_account') return false
if (!Array.isArray(payload.entry) || payload.entry.length === 0) return false
for (const entry of payload.entry) {
if (entry?.id !== wabaId) return false
if (!Array.isArray(entry.changes) || entry.changes.length === 0) return false
for (const change of entry.changes) {
if (typeof change?.field !== 'string') return false
// Management events forwarded by Dualhook have no metadata.phone_number_id.
if (
MESSAGE_PATH_FIELDS.has(change.field) &&
change.value?.metadata?.phone_number_id !== phoneNumberId
) {
return false
}
}
}
return true
}
async function processPayload(payload: Json, db: Db): Promise<void> {
for (const entry of payload.entry) {
for (const change of entry.changes) {
const value: Json = change.value ?? {}
switch (change.field) {
case 'messages':
for (const message of value.messages ?? []) {
if (await isFirstDelivery(db, `message:${message.id}`)) await onCustomerMessage(message)
}
for (const status of value.statuses ?? []) {
if (await isFirstDelivery(db, `status:${status.id}:${status.status}`)) onStatus(status)
}
for (const error of value.errors ?? []) console.error('whatsapp error', error.code)
break
case 'smb_message_echoes': // Coexistence: staff replied from the WhatsApp Business app
for (const echo of value.message_echoes ?? []) {
if (await isFirstDelivery(db, `echo:${echo.id}`)) onStaffReply(echo)
}
break
case 'history': // Coexistence: one-time chat history sync, in chunks
for (const chunk of value.history ?? []) {
console.log('history chunk', chunk.metadata ?? chunk.errors?.map((e: Json) => e.code))
}
break
case 'smb_app_state_sync': // Coexistence: contacts from the WhatsApp Business app
console.log('contact sync', (value.state_sync ?? []).length)
break
default: // management event forwarded by Dualhook, for example a template status
console.log('management event', change.field, value.event ?? '')
}
}
}
}
// Insert the key. A unique violation means this event was handled before.
// Any other failure is logged and the event is processed: a duplicate is better than a lost message.
async function isFirstDelivery(db: Db, key: string): Promise<boolean> {
try {
const { error } = await db.from('whatsapp_webhook_events').insert({ event_key: key })
if (!error) return true
if (error.code === '23505') return false
console.error('dedupe unavailable, processing anyway', error.code, error.message)
} catch (error) {
console.error('dedupe unavailable, processing anyway', error)
}
return true
}
// deno-lint-ignore require-await
async function onCustomerMessage(message: Json): Promise<void> {
console.log('customer message', message.type)
// Your logic goes here. Example: answer with an approved template that has no variables.
// if (message.from) await sendTemplate(message.from, 'opening_hours_v1', 'en_US')
}
function onStaffReply(echo: Json): void {
// A person answered from the app. Do not treat it as a customer message.
console.log('staff reply', echo.type)
}
function onStatus(status: Json): void {
if (status.status === 'failed') {
console.error('send failed', status.errors?.map((e: Json) => e.code))
}
}
// Outbound sends go through the Dualhook Runtime API with the connection's dh_live_ key.
// deno-lint-ignore no-unused-vars
async function sendTemplate(to: string, name: string, languageCode: string): Promise<Json> {
const phoneNumberId = Deno.env.get('WHATSAPP_PHONE_NUMBER_ID')
const apiKey = Deno.env.get('DUALHOOK_API_KEY')
if (!phoneNumberId || !apiKey) {
throw new Error('Missing secret WHATSAPP_PHONE_NUMBER_ID or DUALHOOK_API_KEY')
}
const response = await fetch(`https://api.dualhook.com/v25.0/${phoneNumberId}/messages`, {
method: 'POST',
headers: {
Authorization: `Bearer ${apiKey}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
messaging_product: 'whatsapp',
to,
type: 'template',
template: { name, language: { code: languageCode } },
}),
})
const body: Json = await response.json().catch(() => ({}))
if (!response.ok) {
console.error('send rejected', response.status, response.headers.get('X-Dualhook-Request-Id'))
}
return body
}
Turn Off JWT Verification
By default Supabase checks the Authorization header of every request before your function runs. Meta's deliveries and Dualhook's forwards carry no Supabase credentials, so with the check on they get 401 with Missing authorization header and your code never runs.
Turn the check off for this function only, in supabase/config.toml. The setting takes effect when you deploy:
[functions.whatsapp-webhook]
verify_jwt = false
Two other ways do the same: supabase functions deploy whatsapp-webhook --no-verify-jwt, or in the Dashboard open the function's details and turn off JWT verification.
How this fits Supabase's API keys:
verify_jwtis a platform check for user JWTs. It also lets through a request that carries one of the project's publishable or secret API keys, but Meta sends neither.- In the code,
withSupabasewithauth: 'none'accepts every caller. Supabase documents that mode, together withverify_jwt = false, for external webhooks, and advises verifying the provider's signature in the handler. On a Dualhook connection you cannot, so the secret URL segment and the payload checks take that place. ctx.supabaseAdminstill works. It is a Supabase client that uses the project'sdefaultsecret key from the function's environment, so the key never appears in your code.
Store the Secrets
The function reads its configuration with Deno.env.get, from Supabase's Edge Function secrets:
| Secret | Value | Needed |
|---|---|---|
WEBHOOK_PATH_SECRET | A random string you generate. It is the last segment of the webhook URL | Before you connect |
WHATSAPP_VERIFY_TOKEN | The verify token you enter in Dualhook | Before you connect |
WHATSAPP_WABA_ID | The connection's WABA ID | As soon as signup completes |
WHATSAPP_PHONE_NUMBER_ID | The connection's phone number ID | As soon as signup completes |
DUALHOOK_API_KEY | The connection's dh_live_... key | Before the first send |
Generate the two random values with openssl rand -hex 24, put the secrets in a .env file that is in your .gitignore, and push it:
# .env
WEBHOOK_PATH_SECRET=<first random value>
WHATSAPP_VERIFY_TOKEN=<second random value>
WHATSAPP_WABA_ID=102290129340398
WHATSAPP_PHONE_NUMBER_ID=123456789012345
DUALHOOK_API_KEY=dh_live_your_key
supabase secrets set --env-file .env
In the Dashboard, the same secrets go under Edge Functions > Secrets: enter a Key and a Value, then click Save.
- A secret name cannot start with
SUPABASE_. That prefix is reserved for the variables Supabase injects, such asSUPABASE_URLand the API keys. - A function reads a new secret immediately. You do not need to redeploy.
- For local runs with
supabase functions serve, the same names go insupabase/functions/.env.
The handshake needs only the first two secrets, so you can connect before you know the IDs. Until WHATSAPP_WABA_ID and WHATSAPP_PHONE_NUMBER_ID are both set, the function answers every POST with 503 and the body Not configured, and logs Not configured. Missing secrets: with the names. Set them as soon as signup completes: Meta retries a failed delivery, but on a Coexistence number the one-time history sync starts right after onboarding.
Handle the Verification Handshake
Meta verifies your callback URL with a GET request that includes:
hub.mode=subscribehub.verify_token=<YOUR_VERIFY_TOKEN>hub.challenge=<CHALLENGE_VALUE>
The function answers 200 with the hub.challenge value as a text/plain body when hub.mode is subscribe and hub.verify_token equals WHATSAPP_VERIFY_TOKEN. Any other GET gets 403.
Do not respond with JSON: Meta needs the raw challenge as the body, and Dualhook's setup check reports a JSON-wrapped challenge as a failure.
The verify token is checked on GET only. Real deliveries are POST requests with no hub.verify_token, so a token check on them drops every message. Dualhook uses the verify token you entered during connection setup, so the secret in Supabase and the value stored on the Dualhook connection must match.
Validate the Webhook Payload
The function validates every POST before it accepts the payload: the WhatsApp envelope shape, then the WABA ID and phone_number_id against the secrets you stored for this connection.
Check the envelope, WABA, and phone number
isExpectedPayload checks the envelope first and the field-specific identity second:
objectequalswhatsapp_business_account- every
entry[].idequalsWHATSAPP_WABA_ID - every entry has a non-empty
changesarray, and every change has afield - for message-path fields,
value.metadata.phone_number_idis present and equalsWHATSAPP_PHONE_NUMBER_ID
The same URL receives two kinds of fields:
- Message-path fields, sent by Meta directly:
messages(inbound messages andstatuses), plussmb_message_echoes,historyandsmb_app_state_syncon Coexistence numbers. All four carryvalue.metadata.phone_number_id. - Management fields such as
message_template_status_updateoraccount_update, forwarded by Dualhook with anX-Dualhook-Eventheader and noX-Hub-Signature-256. They have nometadata.phone_number_id, so the function checksentry[].idonly. See Forwarding Headers.
If the envelope or an ID check fails, the function responds 401 and stops. A field it does not process is not a failure: it returns 200 and logs the field name. Meta retries a rejected message-path delivery for up to 7 days, while a rejected management event is lost, because Dualhook forwards each one once.
processPayload then routes on field:
field | What the function does |
|---|---|
messages | Calls onCustomerMessage for each new inbound message and onStatus for each new status |
smb_message_echoes | Calls onStaffReply. A reply your staff sent from the WhatsApp Business app is never handled as a customer message |
history | Logs phase, chunk_order and progress of each chunk, or the error code when the business declined sharing |
smb_app_state_sync | Logs the number of contact changes |
| Any other field | Logs the field name and value.event. These are the management events Dualhook forwards |
The sample event from Dualhook's Test endpoint passes the same checks. The function logs Dualhook Test endpoint ping for it and does nothing else.
Coexistence history sync: right after onboarding, Meta sends the one-time
historysync in chunks, often hundreds of events and up to 3 MB each. Answer every chunk with200, even ones you discard. Once Meta's retries end, Dualhook cannot request a rejected chunk again, and a re-onboard is not guaranteed to bring the history back. If you need the history, write each chunk to your own storage before you answer200, not in the background work: Meta does not send a chunk again once it has a200, and Dualhook has no copy. See History Webhook.
Keep the URL unguessable
The function compares the last path segment of every request with WEBHOOK_PATH_SECRET and answers 404 when it differs, before it looks at anything else. Treat the full URL as a secret: do not paste it into shared chat, do not commit it to repos, and rotate it (set a new WEBHOOK_PATH_SECRET, then update the URL in Dualhook) if it leaks. Meta accepts callback URLs of up to 200 characters, and Dualhook rejects a longer one.
The payload checks above stop stray and casual requests, but anyone who learns your URL and IDs could send a matching payload, so do not let a webhook alone trigger anything irreversible.
Respond Early with a Background Task
For a valid payload the function does no database or network work before it answers:
- It returns
200as soon as the envelope and ID checks pass. - It hands the rest to
EdgeRuntime.waitUntil, Supabase's mechanism for background tasks. The function instance keeps running until that promise completes.
This keeps acknowledgments fast enough for Meta retries to stay rare, and well inside the 15 seconds Dualhook waits when it forwards a management event.
What Supabase documents about background tasks:
- A task ends when the worker reaches a limit: 256 MB of memory, 2 seconds of CPU time, or the wall clock limit of 150 seconds on the Free plan and 400 seconds on paid plans. Time spent waiting on the database or on an HTTP call does not count as CPU time.
- Catch errors inside the task. The function does, and logs
webhook processing failed. - Locally,
supabase functions serveends the instance when the request completes, which cuts background tasks short. For local tests, add this tosupabase/config.toml:
[edge_runtime]
policy = "per_worker"
Deduplicate with a Postgres Table
Meta can deliver the same event more than once. The function claims each event by inserting a key into a table with a primary key. A second insert of the same key fails with Postgres error 23505 (unique violation), and the function skips the event. If the insert fails for any other reason, such as a missing table, the function logs dedupe unavailable, processing anyway and processes the event: the result is duplicates, not lost messages.
Create the table before you connect the number, in the Dashboard's SQL Editor or in a migration:
create table public.whatsapp_webhook_events (
event_key text primary key,
received_at timestamptz not null default now()
);
alter table public.whatsapp_webhook_events enable row level security;
revoke all on table public.whatsapp_webhook_events from anon, authenticated;
grant select, insert, delete on table public.whatsapp_webhook_events to service_role;
- The keys are
message:<id>for inbound messages,status:<id>:<status>for statuses andecho:<id>for staff replies. The table holds message IDs, not message content. ctx.supabaseAdminuses a secret key, which bypasses Row Level Security. With RLS on and no policies, the table cannot be read with a publishable key.- Some projects do not grant privileges on new tables automatically, so the
grantis explicit. ctx.supabaseAdminreaches the table through the project's Data API, so the Data API must be enabled andpublicmust be one of its exposed schemas. Both are the default. With the Data API disabled, none of the auto-generated REST endpoints respond.- The example does not dedupe management events. Dualhook forwards each one once. It drops a management event only when it is identical to the last one logged for the same connection and event type (and, for template events, the same template) within 60 seconds, so make a management handler with side effects idempotent.
Delete old rows on a schedule, and keep them longer than Meta's 7 days of retries:
delete from public.whatsapp_webhook_events where received_at < now() - interval '30 days';
Send Template Messages via Dualhook
The function sends outbound messages through Dualhook's allowlisted runtime. Inbound routing remains direct from Meta.
sendTemplate makes this request with the dh_live_... key from the DUALHOOK_API_KEY secret:
- Method:
POST - URL:
https://api.dualhook.com/v25.0/<PHONE_NUMBER_ID>/messages - Headers:
Authorization: Bearer dh_live_...andContent-Type: application/json
Example template send:
{
"messaging_product": "whatsapp",
"to": "+12015550123",
"type": "template",
"template": {
"name": "opening_hours_v1",
"language": { "code": "en_US" }
}
}
As written, the function sends nothing: the call in onCustomerMessage is commented out. The example assumes an approved template without variables, here the invented opening_hours_v1 in en_US. It checks message.from first, because an inbound message can arrive without it. Call sendTemplate from your own logic, and not for every inbound message: on a Coexistence number your staff may be answering the same chat in the app.
A send from onCustomerMessage runs inside the background task, after the 200. Dualhook never retries a send, and neither does the function. When a send is rejected it logs the HTTP status and the X-Dualhook-Request-Id response header, which you can give to support. An organization admin creates the key under Connection → Overview → Outbound API key, and the plaintext is shown once. See Runtime API Authentication.
For variables, media headers, and button parameters, see Sending Template Messages.
Test with Dualhook
-
Deploy the function with JWT verification off, set
WEBHOOK_PATH_SECRETandWHATSAPP_VERIFY_TOKEN, and create the dedupe table. -
Check the handshake yourself. This should return
200with1903260781as the body:curl -i "https://<project-ref>.supabase.co/functions/v1/whatsapp-webhook/<WEBHOOK_PATH_SECRET>?hub.mode=subscribe&hub.verify_token=<WHATSAPP_VERIFY_TOKEN>&hub.challenge=1903260781" -
Put the full URL, including the secret segment, in Dualhook as the webhook URL, with the same verify token.
-
As soon as signup completes, set
WHATSAPP_WABA_ID,WHATSAPP_PHONE_NUMBER_IDandDUALHOOK_API_KEY. -
Run Dualhook Test endpoint to confirm reachability.
-
Send a real WhatsApp message to your number.
-
Open the function's Logs tab in the Supabase Dashboard and confirm that:
- verification succeeds
- payload validation accepts the sample event from Test endpoint (a Meta-shaped envelope with your WABA and phone number ID, an empty
messagesarray andX-Dualhook-Event: test_ping): the function logsDualhook Test endpoint ping - payload validation accepts the real Meta POST
- the function returns
200quickly - an inbound message logs
customer messageonce - no
dedupe unavailableline appears. If one does, the table is missing or the Data API cannot reach it, and duplicates are not filtered until you fix it - on Coexistence, a reply sent from the WhatsApp Business app logs
staff reply. Also send one message through the Runtime API and check that nostaff replyline appears for it
If requests return 401 with Missing authorization header, JWT verification is still on. If a POST returns 503 with Not configured, a secret is missing and the log names it. If every request returns 500 with MISSING_DEFAULT_PUBLISHABLE_KEY, the project has no default publishable key (see Prerequisites).
Production Caveats
- A background task is not a queue. Once the function has answered
200, Meta does not send the event again, so work that fails or is cut off by a limit is gone. If you cannot lose an event, write it to a table of your own first and process it from there. - Keep message content out of the logs. Supabase keeps what your code prints. The function prints no message content: only field names, message types, counts, sync progress and error codes. Supabase's invocation logs record the request method, path and host, and the path contains the secret segment, so anyone who can read the project's logs can read the webhook URL.
- Keep the
dh_live_...key in Edge Function secrets only. Never put it in browser code or in a table your app can read. - Supabase charges per function invocation, regardless of the response status code. A message you send can return
sent,deliveredandreadstatus webhooks on top of the inbound traffic. - Connections under the same WABA share one webhook URL and verify token. This function accepts one phone number ID, so a second number on the same WABA gets
401until you extend the check to a list of IDs. Each connection has its owndh_live_...key. - Treat WhatsApp webhook payloads as evolving. With Meta's BSUID rollout and later username launch, some fields are conditional, and an inbound message can arrive without
from. See the BSUID webhook changes reference. - If the function runs an AI agent, route on
fieldfirst, so a staff reply insmb_message_echoesis not treated as a customer message. Keep the agent about your own business and give customers a way to reach a person: Meta's terms restrict general-purpose AI assistants, and its policy requires escalation paths when you automate replies. See AI agents on WhatsApp Business and human takeover.
Dualhook Boundary
Dualhook sets the Webhook Override at Meta so message-path webhooks go from Meta straight to your function URL, forwards management events to the same URL once each, and relays your sends through the Runtime API. It is not in the message path: it does not receive, store, re-sign, or replay the webhooks Meta sends to your function, and it does not store message content. Dualhook does not host or deploy the function and has no access to your Supabase project. The project, its secrets, its logs and the dedupe table are yours to run, and Dualhook cannot resend a webhook the function dropped.