What Is a Webhook, and How Do You Handle One Safely?

A webhook is another service calling you to say that something happened. Anyone on the internet can call the same URL, so handling one safely takes more than parsing some JSON.

What Is a Webhook, and How Do You Handle One Safely? — Troiana insight cover

In short

A webhook is an HTTP request that one service sends to your server when an event happens, such as a payment succeeding. To handle one safely, verify its signature using the raw request body, return a 2xx response quickly, process the work in a background job, ignore duplicates using the event ID, and don't assume events arrive in order. Without verification, anyone could fake an event.

What it is

With an API, your code asks another service for information. With a webhook, that service tells your code when something has happened. It's the difference between repeatedly phoning to ask if your parcel has arrived, and being sent a text when it does.

Common examples:

  • A payment succeeds, so Stripe tells your app to grant access
  • A customer's subscription is cancelled
  • Code gets pushed, so GitHub starts a build
  • An email bounces

How it works

  1. You give the provider a public URL on your server.
  2. You choose which events you want.
  3. When one happens, the provider sends an HTTP POST with details, usually as JSON.
  4. Your server responds with a success code, to confirm receipt.
  5. If it doesn't, the provider tries again later.

Stripe's documentation, for example, says that it retries for up to three days in live mode with exponential back-off, so a temporary failure on your side need not lose an event.

Rule 1: verify that it's genuine

Your webhook URL is public. Without verification, an attacker could POST a fake “payment succeeded” event and receive your product for free. Stripe's docs warn of precisely this: an attacker could send fake events to fulfil orders or grant account access.

Providers sign their requests. Use their official library to verify the signature, against the raw request body:

// Express example with Stripe
app.post(
  "/webhooks/stripe",
  express.raw({ type: "application/json" }),
  (req, res) => {
    let event;
    try {
      event = stripe.webhooks.constructEvent(
        req.body,
        req.headers["stripe-signature"],
        process.env.STRIPE_WEBHOOK_SECRET
      );
    } catch (err) {
      return res.status(400).send("Invalid signature");
    }

    // Save it, queue the work, reply fast
    queue.add("stripe-event", { id: event.id, type: event.type });
    res.sendStatus(200);
  }
);

The raw body point catches many people. If your framework parses the JSON first, the bytes change, and verification fails. Developers then sometimes “fix” this by removing the check, which reintroduces the original hole. Keep secrets in environment settings, not in code. See how to handle secrets and API keys.

If you're building your own signature check, use a constant-time comparison, and reject old timestamps to prevent replay. Stripe's libraries have a default tolerance of five minutes.

Rule 2: respond quickly

Stripe says that your endpoint must return a 2xx status “before any complex logic that could cause a timeout”. If you do slow work, such as sending email or updating an accounting system, before responding, the provider may time out and retry, even though you did process the event.

So save the event and return immediately. Do the work in a background job. See background jobs and queues. Queues also protect you from spikes, such as when many subscriptions renew at the start of a month.

Rule 3: expect duplicates

Webhooks are usually delivered at least once, so you'll occasionally get the same event twice. If your handler isn't careful, then a customer could get charged credits twice, or receive two emails.

Make processing idempotent. Store each event ID, and skip any you've already handled:

CREATE TABLE processed_events (
  event_id TEXT PRIMARY KEY,
  processed_at TIMESTAMPTZ DEFAULT now()
);

Insert the ID in the same transaction as your changes. If the insert fails because the ID exists, stop. See what a database transaction is. Stripe also notes that two separate event objects can sometimes describe the same thing, so consider using the object's ID and the event type too.

A safe handler
Verify signatureUsing the raw body
Check event IDSeen it? Skip
Save and return 2xxQuickly
Background jobDoes the real work
A combination of the first three rules. Each step exists because the URL is public, delivery repeats and providers time out.

Rule 4: don't rely on order

Events may arrive out of order. Stripe says plainly that it doesn't guarantee delivery order, and warns against using the created timestamp to work it out. You may get invoice.paid before invoice.created.

So don't write handlers that assume a sequence. A good approach is to treat the event as a signal, and then fetch the current state from the API before acting. That way, an old event can't overwrite newer data.

Rule 5: limit what you trust

  • Use HTTPS only.
  • Listen only to events you need, which reduces load and risk.
  • Don't blindly use data from the event. For sensitive actions, fetch the object from the provider's API.
  • Exempt the route from CSRF protection only, and keep your signature check in place.
  • Consider IP allow-lists if the provider publishes them, as an extra layer.
  • Rotate signing secrets periodically, or if you suspect a leak.
  • Don't expose internal errors in the response.

Vibe-coded apps deserve a special check here, because a webhook that works in a demo may be missing signature verification altogether. See the security checklist.

Testing

Provider tools make this much easier. With Stripe's CLI, you can forward events to your machine and trigger test ones:

stripe listen --forward-to localhost:4242/webhooks/stripe
stripe trigger payment_intent.succeeded

Test these cases:

  • A valid event
  • A bad signature, which must be rejected
  • The same event sent twice
  • Events out of order
  • A failure in your handler. Does the retry work?
  • A slow downstream service

Monitoring

Silent webhook failures are dangerous, as customers can pay and not get access. So:

  • Alert on repeated failures from your endpoint
  • Check your provider's delivery dashboard
  • Store raw events for a period, so you can debug and replay them
  • Run a daily reconciliation between your records and the provider's, for anything involving money

See how to monitor a production app and how to handle failed payments.

Sending webhooks yourself

If your product sends webhooks to others, offer signatures, retries, event IDs and a delivery log. How to design a webhook system covers that side.

If you'd like a review of your payment or integration code, book a call.

Common questions

What is a webhook in simple terms?

It's an automated message that one service sends to your server when something happens, such as a payment succeeding. Rather than you repeatedly asking whether anything has changed, the other service tells you as soon as it does.

How do I secure a webhook?

Verify the provider's signature using the raw request body, use HTTPS, and keep the signing secret out of your code. Check the timestamp to prevent replays, and for sensitive actions, confirm details through the provider's API before you act.

Why am I getting the same webhook twice?

Providers usually deliver events at least once, and they retry when they don't receive a timely success response. Store each event ID, and skip those you've already processed. Respond quickly and do slow work in the background, to reduce retries.

What's the difference between a webhook and an API?

With an API, your code requests information when it needs it. With a webhook, the other service sends you information when an event happens. Many integrations use both: a webhook for the signal and an API call to get the current details.

Have something worth building right?