Skip to content
Guides
Build guide

How to add webhooks in Next.js without processing one twice

A webhook endpoint in the App Router is twenty lines. What decides whether it works is the delivery contract: answer within 15 seconds, dedupe on the event id, and reconcile for what never arrives.

Dharmendra Jagodana7 min read

In short

In the Next.js App Router a webhook endpoint is a POST route handler that reads req.text() for the raw bytes, verifies the signature before parsing anything, records the event id so a retry is not processed twice, and answers inside 15 seconds. On BuildBase that is parseWebhookEvent plus one table of ids.

The signature check is the part every webhook tutorial covers. It is also the part that stops breaking the day you get it right.

What breaks later is the handler that does its work before it answers. BuildBase counts no answer within 15 seconds as a failed attempt, and a failed attempt is retried: five attempts in all, at roughly 10, 20, 40 and 80 seconds, so the last one lands about two and a half minutes after the first.

From the sender's side a slow success and a hard failure look identical. Your handler that "works" has quietly run four more times.

So the dedupe belongs in the same commit as the route, not in the follow-up ticket you are never going to write.

Written against Next.js 14.2.35 and @buildbase/sdk 1.8.0. The route handler is the canonical SDK snippet; the table and the queue call sketch your own code and were not run as written.

Before you start

A BuildBase project and somewhere your app can receive a POST. Outside production that can be an http:// address or a tunnel to your machine; production takes HTTPS only. You will also need a queue or a job runner for step four, because the whole point is that the slow work happens somewhere other than the request.

Step one: create the endpoint, and keep the secret

In the console, open Settings, then Webhooks, then Create webhook. Give it your URL and pick the events you want. There are 256 of them in 43 groups, reaching well past the sign-up and subscription events most people come for, and you can subscribe to a named list or to all of them. Check the event categories table for yours rather than assuming: commerce, content and workflow events are close to a third of the catalog between them.

The sheet then shows the signing secret, once. Copy it into your environment as BUILDBASE_WEBHOOK_SECRET before you close it. If you lose it, rotate it from the console and copy the new one; there is no second viewing of the old one.

Endpoints and secrets belong to one environment. A Development endpoint never receives production's events, production's secret never verifies a Development delivery, and promoting changes between environments copies neither. Add them in each environment you actually use.

What you should see: the endpoint listed, with an empty delivery log.

Step two: the route handler, raw body first

// app/api/webhooks/buildbase/route.ts
import { parseWebhookEvent } from '@buildbase/sdk';

export async function POST(req: Request) {
  const body = await req.text();

  const event = parseWebhookEvent({
    body,
    signature: req.headers.get('x-buildbase-signature'),
    timestamp: req.headers.get('x-buildbase-timestamp'),
    secret: process.env.BUILDBASE_WEBHOOK_SECRET ?? '',
  });

  if (!event) {
    return Response.json({ error: 'Invalid signature' }, { status: 401 });
  }

  return Response.json({ received: true });
}

req.text() is doing more work than it looks. The signature is an HMAC-SHA256 over {timestamp}.{body}, where the body is the exact bytes that were sent. Read the request with await req.json() and you get an object; serialize that object again to hash it and you have changed the whitespace, possibly the key order, and the comparison fails on a delivery that was never tampered with.

A request body can only be read once anyway, so read it as text and let parseWebhookEvent do the parsing from the same string it verified.

One call verifies and parses. It returns null when the signature does not match and null when the delivery is more than five minutes old, and you should keep it that way in your own response: a receiver that tells the two apart tells an attacker which half they got right.

What you should see: trigger any subscribed event and the delivery log in the console shows a 200. Put a deliberately wrong value in your own BUILDBASE_WEBHOOK_SECRET and it shows your 401.

Step three: record the id before you do anything

Every attempt of the same event carries the same id, in the body and in the x-buildbase-event-id header. That id is the only thing that reliably says "you have seen this".

The table is yours, not something the SDK gives you. One column does it:

create table webhook_event (
  id         text primary key,
  seen_at    timestamptz not null default now()
);
// Your own code, with whatever Postgres client you already use.
// Insert-first, not check-then-insert: a retry can arrive while the first
// attempt is still running, and a check would pass in both.
async function claim(id: string) {
  const { rowCount } = await sql`
    insert into webhook_event (id) values (${id}) on conflict do nothing
  `;
  return rowCount === 1;
}

Let the primary key decide, rather than reading and then writing. The two deliveries you most need to separate are the slow original and its retry, and those overlap by definition: the retry is sent because the original has not answered yet.

Watch the id though. It is optional in the SDK's return type, because a body from a platform release older than event ids has none, and one undefined written into a unique column becomes the row that swallows every event after it. Guard it, and treat a missing id as "process this, I cannot tell":

if (!event) {
  return Response.json({ error: 'Invalid signature' }, { status: 401 });
}

if (event.id && !(await claim(event.id))) {
  return Response.json({ duplicate: true });
}

Do not deduplicate on a hash of the body. A retry normally resends the first attempt's exact bytes, but when that copy cannot be read the body is built again, and its data can differ while the id stays put.

What you should see: post the same body and headers to your own route twice, inside the five-minute window, and the second call answers { duplicate: true } while webhook_event gains exactly one row.

Step four: answer, then work

Key takeaway

The 15 seconds is a deadline on your response, measured from the connection to the last byte you send. It is not a budget for your side effects. Verify, record the id, enqueue, answer.

await queue.add('buildbase-event', {
  id: event.id,
  name: event.event,
  data: event.data,
});

return Response.json({ received: true });

A real queue, not a floating promise. On most serverless hosts the function can be frozen or torn down once the response is sent, so work you started and did not await is work that may simply not happen, with a 200 in the delivery log saying it did.

What you should see: the delivery log reporting durations in the tens of milliseconds rather than seconds, whatever the job behind it costs.

Step five: reconcile, because some events never arrive

Delivery is best effort. Take that literally: an event is lost, with no row in the delivery log at all, if it cannot be queued, if looking up your endpoints fails in that moment, or if the server stops between saving the change and dispatching the event.

A delivery that fails all five attempts is not sent again either. Only one that sent nothing keeps its event: a throttled delivery, or one skipped while BuildBase had the endpoint auto-disabled. Those you can send again once each, and only to an endpoint that is currently on, by posting to /api/organizations/webhooks/:id/deliveries/:deliveryId/redeliver. There is no button for it in the console, so this is a call you make yourself, and it counts against the per-minute budget like any other delivery. An endpoint you switched off yourself logs nothing, so it has nothing to resend.

So a webhook is a speed-up, not a system of record. If missing a change would cost you money or correctness, read the authoritative state back with the server SDK on a schedule and fix the differences. How often? That depends on what a missed event costs you, and only you can price that, so I will not invent a number here.

What you should see: the first reconcile run finds differences, and later runs find almost none. One that keeps finding them is telling you something about your handler rather than about the reconcile.

The failure modes worth knowing

Middleware eats it. A matcher covering /api sends your webhook through an auth check it cannot pass, because a webhook arrives with a signature and no session. The symptom is a delivery log full of 307s or 401s your handler never issued. Exclude the path.

Order is not given. Events can arrive out of order, and a retry alone guarantees it: an event that lands on its fourth attempt arrives after events created later. Compare event.timestamp against what you have stored rather than trusting arrival order.

410 does not mean stop. Every status other than 2xx is retried the same way, 410 Gone included. To stop deliveries, turn the endpoint off or remove it in the console, which also drops its pending retries.

The endpoint turns itself off. Fifty consecutive failed deliveries, failing for at least an hour, auto-disable an endpoint and email the owner and admins. Any 2xx resets the count. This is a feature on the day a deploy breaks your handler and a surprise on the day you did not notice.

One wildcard endpoint, then a campaign. An organization gets 240 deliveries a minute across all its endpoints, and email.sent fires once per recipient. A large send is exactly the shape that hits it. Deliveries over the budget are not silently dropped: they log as throttled, the first 20 rows an endpoint gets in a minute individually and the rest of that minute as one summary row you cannot resend from. payment.* and subscription.* are always sent, though they still count toward the limit.

Install

npm i @buildbase/sdk
webhooks
nextjs
events

Frequently Asked Questions

Do I need a separate API route for webhooks in the Next.js App Router?

One app/api/webhooks/buildbase/route.ts exporting POST is enough. Keep it outside any auth middleware, because a webhook arrives with a signature rather than a session, and read the body with req.text() so the exact bytes survive for the signature check.

How fast does a Next.js webhook handler have to respond?

BuildBase counts no answer within 15 seconds as a failed attempt and retries, so a handler slower than that turns one event into several deliveries of the same event. The 15 seconds is a deadline on your response, not a budget for your side effects: verify, write the event id, enqueue the work, answer, and do the slow part in a job.

How do I stop a webhook from being processed twice?

Store the event id, which arrives both in the body as id and in the x-buildbase-event-id header, and skip an id you have already recorded. Deduplicate on the id rather than a hash of the body: a retry can rebuild the body and its data can differ, while the id is the same on every attempt and for every endpoint the event reaches.

Can I test a Next.js webhook handler on localhost?

Outside production an endpoint may be an http:// address or a tunnel, so a receiver on your own machine works while you build. Production takes HTTPS only. Endpoints and signing secrets belong to one environment each, and promotion never copies them, so add them again in each environment.

Ship it

Create a project and run this guide against your own workspace.

Free plan7-day free trial on paid plansNo credit card required