WhatsApp Cloud API With Supabase Edge Functions

Use Supabase Edge Functions with the WhatsApp Cloud API: a send function, a signed webhook that saves messages to Postgres, secrets, and the Firebase version.

Illustration: two serverless functions linking a database table to a phone receiving a WhatsApp message (sample data)

To use the WhatsApp Cloud API with Supabase, write two Edge Functions: one that POSTs to https://graph.facebook.com/v27.0/<PHONE_NUMBER_ID>/messages with your token from Supabase secrets, and one that receives Meta’s webhook, checks the X-Hub-Signature-256 signature and saves messages to Postgres. The webhook function needs verify_jwt = false, because Meta doesn’t send Supabase credentials.

This guide gives the code for both functions, the table, the secrets and the deploy steps, using Graph API v27.0 (the latest in Meta’s changelog, released on 4 November 2026). Near the end, the same webhook on Firebase Cloud Functions, for anyone who searched for the Firebase WhatsApp API.

Key takeaways

  • Two functions: whatsapp-send (called by your server or a schedule) and whatsapp-webhook (called by Meta).
  • Keep the WhatsApp token and app secret in Supabase secrets and read them with Deno.env.get. They take effect without a redeploy.
  • Set verify_jwt = false for both, then protect each in code: the secret key for sending, Meta’s signature for the webhook.
  • Hash the raw body bytes with Web Crypto, and only then parse the JSON.
  • Save messages with an upsert on the message ID, because Meta retries and can send the same message twice.

How the pieces fit together

PieceWho calls itWhat it doesHow it’s protected
whatsapp-send functionYour backend, or pg_cron on a scheduleSends an approved template through the Cloud APISupabase secret key in the apikey header (auth: 'secret')
whatsapp-webhook functionMetaAnswers the handshake, checks the signature, saves messagesMeta’s X-Hub-Signature-256 (auth: 'none' plus your own check)
whatsapp_messages tableThe webhook functionKeeps incoming messages, one row per message IDRow Level Security on, with no policies

Never call the send function from a browser or mobile app with the secret key: it bypasses Row Level Security. If your front end needs to send, call it with a user’s login instead (auth: 'user') and check in the function that the user may message that customer.

Before you start: Meta values and Supabase secrets

  • From Meta: your phone number ID (where to find it), a permanent system-user token (Cloud API setup), your app secret, and an approved template. Test with your own phone on Meta’s test number.
  • From Supabase: a project, the Supabase CLI, and Docker if you want to run functions locally.
  • A verify token you make up, for the webhook handshake.

Create the functions with supabase functions new whatsapp-send and supabase functions new whatsapp-webhook; each gets supabase/functions/<name>/index.ts. Then add the secrets:

  1. For local runs, put them in supabase/functions/.env as WHATSAPP_TOKEN=…, WHATSAPP_PHONE_NUMBER_ID=…, META_APP_SECRET=… and META_VERIFY_TOKEN=…, and add that file to .gitignore.
  2. For production, run supabase secrets set --env-file supabase/functions/.env, or set each one with supabase secrets set NAME=value. Check with supabase secrets list.
  3. Names can’t start with SUPABASE_; that prefix is reserved for the defaults Supabase provides, such as SUPABASE_URL.

Then turn off the platform’s JWT check for both functions in supabase/config.toml, as Supabase’s docs advise for webhooks:

Linesupabase/config.toml
1[functions.whatsapp-send]
2verify_jwt = false
3[functions.whatsapp-webhook]
4verify_jwt = false

A send function

This sends the template order_update (“Hi {{1}}, your order {{2}} has shipped.”) to one customer. Templates are what you can send to people who haven’t written to you in the last 24 hours, and only to people who opted in.

Linesupabase/functions/whatsapp-send/index.ts
1import { withSupabase } from 'npm:@supabase/server@1';
2const GRAPH = 'https://graph.facebook.com/v27.0/';
3export default { fetch: withSupabase({ auth: 'secret' }, async (req) => {
4 const { to, name, orderId } = await req.json();
5 const message = { messaging_product: 'whatsapp', recipient_type: 'individual', to, type: 'template', template: { name: 'order_update', language: { code: 'en' }, components: [{ type: 'body', parameters: [{ type: 'text', text: name }, { type: 'text', text: orderId }] }] } };
6 const res = await fetch(GRAPH + Deno.env.get('WHATSAPP_PHONE_NUMBER_ID') + '/messages', { method: 'POST', headers: { Authorization: 'Bearer ' + Deno.env.get('WHATSAPP_TOKEN'), 'Content-Type': 'application/json' }, body: JSON.stringify(message) });
7 const data = await res.json();
8 if (data.error) return Response.json({ code: data.error.code, message: data.error.message }, { status: 502 });
9 return Response.json({ id: data.messages[0].id });
10}) };
  • The template must be APPROVED, with a name and language code that match WhatsApp Manager exactly. For named variables, add parameter_name to each value.
  • The returned ID (wamid…) is what delivery statuses refer to. Success means Meta accepted the message, not that it was delivered.
  • Errors come back with Meta’s code: 190 is an expired token, 131047 means you tried free text outside the 24-hour window, 132001 is a wrong template name or language, and 130429 means slow down. The full list is in WhatsApp API error codes.

Call it from your backend with curl -X POST https://<project-ref>.supabase.co/functions/v1/whatsapp-send -H "apikey: <secret key>" -H "Content-Type: application/json" -d '{"to":"919800000000","name":"Priya","orderId":"ORD-1042"}'. To send on a schedule, Supabase documents calling a function from pg_cron with pg_net, keeping the project URL and secret key in Vault. Its docs warn that the decrypted key sits in net.http_request_queue until the request goes out, readable by any database role that can log in.

A webhook function that checks Meta’s signature

Meta sends a GET handshake when you save the callback URL, then signed POSTs with messages and statuses. Deno has Web Crypto built in, so no extra package is needed for the HMAC:

Linesupabase/functions/whatsapp-webhook/index.ts
1import { withSupabase } from 'npm:@supabase/server@1';
2function hexToBytes(hex: string) { return /^[0-9a-f]{64}$/i.test(hex) ? Uint8Array.from(hex.match(/../g) ?? [], (h) => parseInt(h, 16)) : null; }
3async function validSignature(body: Uint8Array, header: string | null) {
4 const secret = Deno.env.get('META_APP_SECRET'); const sig = header?.startsWith('sha256=') ? hexToBytes(header.slice(7)) : null;
5 if (!secret || !sig) return false;
6 const key = await crypto.subtle.importKey('raw', new TextEncoder().encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['verify']);
7 return crypto.subtle.verify('HMAC', key, sig, body); }
8export default { fetch: withSupabase({ auth: 'none' }, async (req, ctx) => {
9 const q = new URL(req.url).searchParams;
10 if (req.method === 'GET') return q.get('hub.mode') === 'subscribe' && q.get('hub.verify_token') === Deno.env.get('META_VERIFY_TOKEN') ? new Response(q.get('hub.challenge') ?? '') : new Response('forbidden', { status: 403 });
11 const raw = new Uint8Array(await req.arrayBuffer());
12 if (!(await validSignature(raw, req.headers.get('x-hub-signature-256')))) return new Response('invalid signature', { status: 401 });
13 const update = JSON.parse(new TextDecoder().decode(raw));
14 const rows = (update.entry ?? []).flatMap((e: any) => (e.changes ?? []).flatMap((c: any) => (c.value?.messages ?? []).map((m: any) => ({ wamid: m.id, from_number: m.from, type: m.type, body: m.text?.body ?? null, raw: m }))));
15 if (rows.length) { const { error } = await ctx.supabaseAdmin.from('whatsapp_messages').upsert(rows, { onConflict: 'wamid', ignoreDuplicates: true }); if (error) return new Response('db error', { status: 500 }); }
16 return new Response('OK');
17}) };
  1. Handshake (line 10): Meta sends hub.mode=subscribe, your verify token and a random hub.challenge. Return the challenge with a 200; Meta sends nothing until this passes.
  2. Signature (lines 2 to 7, 11 and 12): the header is sha256= plus the hex HMAC-SHA256 of the raw body, keyed with your app secret. crypto.subtle.verify does the comparison for you, so you never compare strings yourself.
  3. Raw bytes first (line 11): read the body once as bytes, check them, then decode and parse. Parsing first and re-serialising would change the bytes and break the check.
  4. Save, then answer (lines 15 and 16): a 500 on a database error makes Meta retry later, for up to 7 days, so nothing is lost. The upsert ignores a message ID it has already saved.

The messages table

Run this in the SQL editor. Row Level Security with no policies means only server-side code using the admin client (as the webhook does) can read or write it:

LineSQL
1create table whatsapp_messages (wamid text primary key, from_number text, type text, body text, raw jsonb, received_at timestamptz default now());
2alter table whatsapp_messages enable row level security;

from_number is the sender’s WhatsApp ID, body is the text for text messages (empty for images or buttons, whose details stay in raw), and wamid is Meta’s message ID. Payload shapes for every message type are in WhatsApp Cloud API webhooks.

Deploy, connect to Meta and test

  1. Run locally: supabase start, then supabase functions serve. Functions answer at http://localhost:54321/functions/v1/<name>.
  2. Test the handshake: curl "http://localhost:54321/functions/v1/whatsapp-webhook?hub.mode=subscribe&hub.verify_token=$META_VERIFY_TOKEN&hub.challenge=12345" should print 12345.
  3. Test the signature: set BODY='{"entry":[]}' and SIG=$(printf %s "$BODY" | openssl dgst -sha256 -hmac "$META_APP_SECRET" | awk '{print $NF}'), then POST it with the header X-Hub-Signature-256: sha256=$SIG. You should get 200, and 401 if you change one character.
  4. Deploy: supabase functions deploy deploys every function. The production URL is https://<project-ref>.supabase.co/functions/v1/whatsapp-webhook, already on HTTPS with a valid certificate, which Meta requires.
  5. Connect Meta: in your Meta app’s WhatsApp configuration, save that URL and your verify token as the callback URL, then subscribe to the messages field. Send your business number a message and check the table.
Supabase limit (hosted)Value
Memory256 MB
Wall clock per request150 seconds on Free, 400 on paid plans
CPU time2 seconds, not counting time spent waiting on the network
Request idle timeout150 seconds, then a 504

A webhook that verifies, saves and answers stays well inside these. If events don’t arrive, work through WhatsApp webhook not receiving messages.

The same webhook on Firebase Cloud Functions

Firebase works the same way with Node.js. Store the values with firebase functions:secrets:set META_APP_SECRET (and the same for META_VERIFY_TOKEN), bind them to the function, and read them with .value(). Unlike Supabase, Firebase says you must redeploy functions after changing a secret, and secrets live in Google Cloud Secret Manager, a paid service with a free tier.

Linefunctions/index.js
1const { onRequest } = require('firebase-functions/v2/https'); const { defineSecret } = require('firebase-functions/params'); const crypto = require('node:crypto');
2const appSecret = defineSecret('META_APP_SECRET'); const verifyToken = defineSecret('META_VERIFY_TOKEN');
3exports.whatsappWebhook = onRequest({ secrets: [appSecret, verifyToken] }, (req, res) => {
4 if (req.method === 'GET') { if (req.query['hub.mode'] === 'subscribe' && req.query['hub.verify_token'] === verifyToken.value()) res.status(200).send(req.query['hub.challenge']); else res.status(403).send('forbidden'); return; }
5 const expected = Buffer.from('sha256=' + crypto.createHmac('sha256', appSecret.value()).update(req.rawBody).digest('hex'));
6 const given = Buffer.from(req.get('x-hub-signature-256') || '');
7 if (given.length !== expected.length || !crypto.timingSafeEqual(given, expected)) { res.status(401).send('invalid signature'); return; }
8 res.status(200).send('OK');
9});

Google’s docs say you can read both req.body and req.rawBody; hash rawBody, never the parsed object. Every path ends with send(), as Firebase asks, so the function doesn’t keep running. Save messages to Firestore after line 7, before the 200.

Supabase with Automate AI, or no code at all

If you’d rather not run Meta’s webhook yourself, Automate AI connects your number, receives Meta’s webhooks and gives your team a shared inbox, campaigns for approved templates, and no-code chatbots.

You can still keep your data in Supabase. Automate AI’s developer webhooks can POST events such as message.received and message.status.update to an Edge Function. They’re signed differently from Meta’s: an X-Webhook-Signature header holding the hex HMAC-SHA256 of the JSON body, keyed with the secret you get when you create the webhook. Use the same HMAC check, but read X-Webhook-Signature and hex-decode the whole value, since there’s no sha256= prefix. The body is Automate AI’s event JSON, not Meta’s entry and changes, so map its fields to your table. Your send function can call Automate AI’s REST API with an API key instead of Meta’s token. The API and webhooks come with the AI + Automation Plan and Series 4; see the WhatsApp Business API page and pricing.

Frequently asked questions

Can I use the WhatsApp Cloud API with Supabase?

Yes. Write an Edge Function that POSTs to https://graph.facebook.com/v27.0/<PHONE_NUMBER_ID>/messages with a Bearer token from Supabase secrets, and another that receives Meta’s webhook.

Why does Meta get a 401 from my Supabase function?

Edge Functions check for a Supabase JWT by default (verify_jwt = true), and Meta doesn’t send one. Set verify_jwt = false for the webhook function in supabase/config.toml and check Meta’s signature in code instead.

How do I verify the WhatsApp webhook signature in Deno?

Read the body with req.arrayBuffer(), import your app secret as an HMAC SHA-256 key with crypto.subtle.importKey, hex-decode the part after sha256= in X-Hub-Signature-256, and call crypto.subtle.verify.

Do I need to redeploy after changing a Supabase secret?

No. Supabase says functions pick up a new secret immediately. On Firebase, you do need to redeploy.

Does this work with Firebase instead of Supabase?

Yes. Use onRequest from firebase-functions/v2/https, keep the app secret with defineSecret, and hash req.rawBody with Node’s crypto to check the signature.

Can my app send messages to anyone this way?

Only to people who opted in, and outside the 24-hour customer service window only with an approved template.

Sources

  1. Meta: Send messages
  2. Meta: Create a webhook endpoint
  3. Meta: Templates overview
  4. Supabase: Managing secrets
  5. Supabase: Securing Edge Functions
  6. Supabase: Edge Function limits
  7. Firebase: Configure your environment
  8. Google Cloud: Write HTTP functions

WhatsApp rules and prices change. We check these guides against Meta’s documentation, but always confirm current terms with Meta before you rely on them. Questions? Message us on WhatsApp at +91 836 977 8812.