Web Development

What is Webhook?

An HTTP callback: a provider sends an HTTP POST to a URL you register whenever a specific event happens, so you do not have to poll for changes.

Definition

A webhook is an HTTP request that one application sends automatically to another when an event occurs. You give the provider a URL, choose the events you care about (payment succeeded, code pushed, form submitted), and from then on the provider sends an HTTP POST with a JSON description of each event to that URL as it happens. Webhooks are sometimes called reverse APIs or HTTP callbacks, because the provider calls you instead of you calling the provider. A webhook URL is simply the endpoint on your server that receives those requests, for example https://example.com/webhooks/stripe. It must be reachable from the public internet, should use HTTPS, must accept POST requests from the provider, and should respond quickly. During development, tunnelling tools such as ngrok, or a provider's own CLI such as the Stripe CLI, forward events to localhost. Webhook vs API is really push vs pull. With a regular API you poll: ask every minute whether anything changed, which wastes requests when nothing has and adds delay when something has. With a webhook the provider pushes the event the moment it happens. The two are complementary: most providers offer an API for reading and writing data and webhooks for announcing changes, and many handlers respond to a webhook by calling the API to fetch the current state. How webhooks work in practice: the provider records the event, signs the payload, sends it, and waits for a 2xx response. Because the URL is public, anyone could post fake events to it, so providers sign each request, typically with an HMAC-SHA256 of the raw request body using a secret shared at registration, carried in a header such as Stripe-Signature or X-Hub-Signature-256. Your handler recomputes the HMAC, compares it in constant time, and rejects mismatches; including a timestamp in the signed data limits replay attacks. If your endpoint times out or returns an error, the provider retries with backoff (Stripe keeps trying for up to three days in live mode). Retries and network failures mean the same event can arrive more than once or out of order, so handlers must be idempotent: record each event ID and skip ones already processed.

When to Use Webhook

Use webhooks when you need to react quickly to events in another system and that system offers them: payments, Git pushes, CI results, form submissions, CRM updates, chat messages. They cut latency and API usage compared with polling. Prefer polling, or combine the two, when you cannot expose a public HTTPS endpoint, when the provider has no webhooks, or when missing an event would be costly; a periodic reconciliation job that lists recent changes through the API catches anything a failed delivery missed. Design the receiving endpoint to acknowledge fast: verify the signature, store or enqueue the event, return 2xx, and do slow work (sending email, calling other APIs) in a background job. Webhooks are for server-to-server notifications; to push live updates to a browser, use WebSockets or server-sent events.

Webhook in Practice

  • A GitHub push webhook as it arrives at your server (abridged): POST /webhooks/github HTTP/1.1 Host: example.com Content-Type: application/json X-GitHub-Event: push X-GitHub-Delivery: 72d3162e-cc78-11e3-81ab-4c9367dc0958 X-Hub-Signature-256: sha256=757107ea0eb2509fc211221cce984b8a37570b6d7586c22c46f4379c8b043e17 {"ref": "refs/heads/main", "repository": {"full_name": "acme/web"}, ...}
  • Verifying the HMAC signature in Node.js (Express), using the raw body rather than parsed JSON: import crypto from 'node:crypto'; app.post('/webhooks/github', express.raw({ type: 'application/json' }), (req, res) => { const expected = 'sha256=' + crypto.createHmac('sha256', process.env.WEBHOOK_SECRET).update(req.body).digest('hex'); const given = req.get('X-Hub-Signature-256') || ''; if (given.length !== expected.length || !crypto.timingSafeEqual(Buffer.from(given), Buffer.from(expected))) { return res.sendStatus(401); } queue.add(JSON.parse(req.body)); res.sendStatus(202); });
  • Idempotent processing: before acting on a Stripe event, run INSERT INTO processed_events (event_id) VALUES ($1) ON CONFLICT DO NOTHING. If no row was inserted, the event was already handled, so the handler returns 200 without fulfilling the order a second time.
  • Instead of polling a payment provider's API every 30 seconds for 10,000 pending orders, a shop registers a webhook for payment_intent.succeeded. Fulfilment starts within seconds of payment, and the shop makes no requests at all during quiet periods.

Common Mistakes

  • Skipping signature verification, so anyone who discovers the URL can forge 'payment succeeded' events.
  • Computing the HMAC over parsed and re-serialised JSON instead of the raw body. Any change in whitespace or key order breaks the signature; capture the raw bytes first.
  • Doing heavy work before responding. Providers time out after a few seconds (GitHub expects a response within 10) and then retry, which causes duplicate processing.
  • Assuming exactly-once, in-order delivery. Events can repeat or arrive out of order; deduplicate by event ID and check timestamps or fetch current state from the API.
  • Returning 200 when processing failed just to stop retries, which silently drops events. Return an error so the provider retries, and alert on repeated failures.

Keep the references coming

One email a week: new and trending developer tools, fresh comparisons, and what shipped. Unsubscribe in one click.