In EventsIQ, leads arrive by webhook. Meta, TikTok, Snapchat and Google each call a URL the moment someone fills in a lead form. Every lead is money, so the webhook handlers are some of the most careful code in the app.
These are Next.js App Router route handlers. Here is what I learned building them.
The basic shape
A webhook handler has four jobs, in this order:
- Read the raw body.
- Check it really came from the sender.
- Reply quickly, with the status code the sender expects.
- Do the slow work afterwards.
The interesting part is where "store the lead" goes, and that depends on the sender.
Read the raw body first
Signatures are computed over the exact bytes that were sent. If you parse the JSON first and turn it back into a string, the bytes can change (spacing, key order, number formats) and a valid signature stops matching.
So always start with request.text():
export const dynamic = "force-dynamic";
export async function POST(request: Request) {
const rawBody = await request.text(); // before any parsing
const signature = request.headers.get("x-hub-signature-256");
if (!verifyMetaSignature(rawBody, signature, process.env.FACEBOOK_APP_SECRET)) {
return new Response("Invalid signature", { status: 403 });
}
const payload = JSON.parse(rawBody);
// ...
}
Stripe works the same way. If your Stripe webhook ever said "No signatures found matching the expected signature", this is usually why.
Compare signatures in constant time
Meta signs each delivery with your app secret using HMAC SHA-256. The check is short, but use a constant-time comparison. A normal === stops at the first different character, which can leak how much of a guess was right.
import { createHmac, timingSafeEqual } from "crypto";
export function verifyMetaSignature(rawBody: string, header: string | null, secret?: string) {
if (!header || !secret) return false;
const [algorithm, provided] = header.split("=");
if (algorithm !== "sha256" || !provided) return false;
const expected = createHmac("sha256", secret).update(rawBody, "utf8").digest("hex");
const a = Buffer.from(expected);
const b = Buffer.from(provided);
return a.length === b.length && timingSafeEqual(a, b);
}
Not every sender signs. Google lead form webhooks put a key you choose inside the body as google_key. Anyone who has that key can send a fake lead, so compare it in constant time too, and keep it encrypted in your database.
Two senders, two contracts
This is the part that surprised me. "Return 200 fast and do the work later" is the usual advice, but whether it is safe depends on what happens if you lose the work.

Meta: reply first
A Meta lead webhook does not contain the lead. It carries a leadgen_id, and you fetch the lead from the Graph API with the Page's token. Meta retries on any non-2xx and expects a quick answer.
Meta also lets you list a form's leads later. So EventsIQ runs a reconcile sweep that fetches anything a webhook missed. With that safety net, the handler can reply 200 straight away and do everything else in after().
Google: store first
Google lead forms send the full lead in the webhook, and Google has no API to read submissions later. If you do not store the lead during the request, it is gone.
Google's contract is clear:
- 200: stored, or recognised as a duplicate.
- 4xx: permanently wrong (bad key, unknown form). Do not retry.
- 5xx: we broke. Please retry.
So the Google handler writes the lead before it replies. If the database write fails, it can honestly answer 5xx and Google sends the lead again. Only the slow routing is deferred.
The lesson: decide per sender. If you have a second way to get the data, reply first. If you do not, store first and use status codes as your safety net.
Move slow work into after()
Next.js has after() from next/server. It runs a function after the response has been sent, and the platform keeps the function alive until it finishes.
import { after } from "next/server";
export async function POST(request: Request) {
const rawBody = await request.text();
if (!verifyMetaSignature(rawBody, request.headers.get("x-hub-signature-256"), process.env.FACEBOOK_APP_SECRET)) {
return new Response("Invalid signature", { status: 403 });
}
const events = parseLeadgenEvents(rawBody);
after(async () => {
// A few at a time: busy forms send several leads in one delivery.
await mapWithConcurrency(events, 3, async (event) => {
try {
await processLeadgenEvent(event); // fetch from Graph, store, route
} catch {
// One bad event must not stop the rest. The sweep will see it again.
}
});
});
return Response.json({ received: true });
}
Three details:
- Limit concurrency. Meta batches leads from busy forms into one delivery. Run a few at a time, not all at once.
- Catch per item. One broken event should never stop the rest of the batch.
- Reply 200 to junk you cannot fix. If the body is not valid JSON, retrying will not help. Acknowledge it and log it, or the sender will retry forever.
Deduplicate with the sender's own id
Every sender says the same thing in its docs: a webhook may arrive more than once. Use the sender's id as a unique key in the database: leadgen_id for Meta, Google's lead id for Google. A second delivery then hits the unique index and becomes a no-op, and you still answer 200.
Only keep what is yours
Meta subscriptions are per Page, not per form. Once a Page is subscribed, events arrive for every lead form on it, including forms the customer never connected to EventsIQ. If an event does not match a form someone connected, drop it without fetching the lead. Storing another business's personal data because you share a Page is a privacy problem.
Keep webhook routes public
Webhook URLs must not sit behind your login. If your proxy.ts (formerly middleware) protects routes, make sure the webhook paths are outside its list, or the sender gets a sign-in page instead of your handler. In EventsIQ the proxy matcher skips /api entirely, and every webhook proves itself by signature or key instead.
Checklist
- Read the raw body before parsing.
- Verify the signature or key, in constant time.
- Store before replying when the sender gives you no second chance. Otherwise reply first.
- Use status codes the way the sender documents them.
- Put slow work in
after(), with limited concurrency and a try/catch per item. - Deduplicate on the sender's own id.
- Drop events you have no right to keep.
Let's Work Together
If you are building integrations that receive webhooks, contact me here: LinkedIn
