A webhook endpoint is a URL on your server that another service sends an HTTP POST to whenever something happens, together with the code behind that URL that checks the request and acts on it. The sender decides when to call; your endpoint's job is to accept the request, prove it is genuine, answer quickly and make sure the event is handled exactly once.
If webhooks are new to you, start with what webhooks are. This guide covers the receiving side: what an endpoint has to get right, working code for Express, Next.js and FastAPI, the queue-then-process pattern that keeps it fast, and the failures that show up in production.
Webhook endpoint, webhook URL, webhook handler
The words get used interchangeably; the difference matters when something breaks.
| Term | What it is | Example |
|---|---|---|
| Webhook | The event notification itself: one HTTP request with a body describing what happened. | A POST saying flight TK1848's gate changed from A11 to A22 |
| Webhook URL | The address you give the sender. | https://api.example.com/hooks/flights |
| Webhook endpoint | The URL plus the route and handler that answer it. | The POST /hooks/flights route in your service |
| Handler or consumer | The code that does the actual work: updating a booking, sending a push. | A worker that reads the event from a queue |
The endpoint faces the internet. The handler can live somewhere else entirely, and in a well-built receiver it usually does.
What a webhook endpoint has to do
Every sender has its own payload, but the receiving side's requirements are nearly identical everywhere.
Be reachable from the public internet, over HTTPS. The sender is another company's server, so localhost and private addresses are out. Stripe requires publicly accessible HTTPS URLs for registered endpoints, and GitHub's best practices tell you to use HTTPS. Even where plain HTTP is accepted, use HTTPS: the body travels in the clear otherwise. During development a tunnel gives your laptop a public HTTPS address.
Answer with a 2xx fast. Senders put a timeout on every delivery. GitHub expects a 2xx within 10 seconds; FlightByte allows ten seconds before it counts the attempt as failed and retries. Ten seconds sounds generous until your database has a slow minute. The fix is structural, not a faster query: acknowledge first, work later.
Keep the raw body. Signed webhooks are signed over the exact bytes sent. If your framework parses the JSON before your code runs and you re-serialize it to check the signature, the bytes differ and every delivery fails verification. Get the bytes, verify, then parse.
Verify the signature. The URL is not a secret: it shows up in logs, dashboards and screenshots. The signature, an HMAC of the body with a shared secret, is what proves the request came from the sender. Verifying webhook signatures covers the three common mistakes in depth.
Be idempotent. Retries happen, and a retry is the same event again. Every serious sender gives each event an id that stays the same across attempts; store the ids you have processed and treat a repeat as already done.
Return status codes the sender understands. The status code is the only thing the sender learns from your endpoint, and it decides what happens next.
| You return | What it tells the sender | Typical sender behavior |
|---|---|---|
200, 202, 204 | Received. | Done, no retry. |
401 or 400 | This request is wrong and will stay wrong. | Usually not retried. FlightByte does not retry 4xx other than 408 and 429. |
429 | Slow down. | Retried with backoff. |
500, 503, timeout | Something on my side failed. | Retried with backoff. |
301, 302 | Go elsewhere. | Often a failure. Stripe counts redirects as failed deliveries. |
So never answer 500 for a bad signature, or the sender keeps retrying a request you will never accept. And never answer 200 before the event is durably recorded, or a crash in between loses it.
A webhook endpoint in Express
Every Node.js example below shares this verifier. It parses the t=…,v1=… header, rejects stale timestamps and compares in constant time:
// verify.ts
import { createHmac, timingSafeEqual } from "node:crypto";
export function verify(secret: string, header: string, rawBody: Buffer, toleranceSeconds = 300): boolean {
const parts = Object.fromEntries(header.split(",").map((part) => part.split("=", 2)));
const t = Number(parts.t);
if (!Number.isFinite(t) || !parts.v1) return false;
if (Math.abs(Date.now() / 1000 - t) > toleranceSeconds) return false;
const expected = createHmac("sha256", secret).update(`${parts.t}.`).update(rawBody).digest("hex");
return parts.v1.length === expected.length && timingSafeEqual(Buffer.from(parts.v1), Buffer.from(expected));
}The endpoint mounts express.raw on its own route so the body arrives as a Buffer, records the event in an inbox table, and answers 204:
// server.ts
import express from "express";
import pg from "pg";
import { verify } from "./verify.js";
const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });
const SECRET = process.env.FLIGHTBYTE_WEBHOOK_SECRET!;
const app = express();
app.post("/hooks/flights", express.raw({ type: "application/json", limit: "1mb" }), async (req, res) => {
const raw = req.body as Buffer;
if (!verify(SECRET, req.header("x-flightbyte-signature") ?? "", raw)) {
return res.status(401).end();
}
const event = JSON.parse(raw.toString("utf8"));
// Record first, acknowledge second. A repeated id is a no-op, so retries are safe.
await pool.query(
"insert into webhook_inbox (event_id, type, body) values ($1, $2, $3) on conflict (event_id) do nothing",
[event.id, event.type, raw.toString("utf8")],
);
res.status(204).end();
});
app.use(express.json()); // the rest of your API keeps its usual parser
app.listen(3000);Two details carry weight. The raw parser is mounted on this route only, before express.json() can consume the stream. And the limit is raised from body-parser's default of 100 KB, because events that carry a full snapshot can be large; a body over the limit gets a 413 before your code runs.
A webhook endpoint as a Next.js route handler
In the App Router a route handler receives a standard Request, so there is no body parser to disable. Read the bytes with arrayBuffer() rather than json():
// app/hooks/flights/route.ts
import { verify } from "@/lib/verify";
import { pool } from "@/lib/db";
export async function POST(request: Request) {
const raw = Buffer.from(await request.arrayBuffer());
const header = request.headers.get("x-flightbyte-signature") ?? "";
if (!verify(process.env.FLIGHTBYTE_WEBHOOK_SECRET!, header, raw)) {
return new Response(null, { status: 401 });
}
const event = JSON.parse(raw.toString("utf8"));
await pool.query(
"insert into webhook_inbox (event_id, type, body) values ($1, $2, $3) on conflict (event_id) do nothing",
[event.id, event.type, raw.toString("utf8")],
);
return new Response(null, { status: 204 });
}On serverless hosting the function stops when the response is sent, so do not fire off slow work and hope it finishes. Next.js has after() for small follow-up tasks, but it runs within the route's maximum duration and is not retried if it fails. For anything that matters, write to the inbox or a queue as above and let a worker pick it up.
A webhook endpoint in FastAPI
FastAPI parses bodies into models when you declare one as a parameter, which is exactly what you do not want here. Take the Request and read await request.body():
import hashlib, hmac, json, os, time
from contextlib import asynccontextmanager
import asyncpg
from fastapi import FastAPI, HTTPException, Request, Response
SECRET = os.environ["FLIGHTBYTE_WEBHOOK_SECRET"].encode()
def verify(secret: bytes, header: str, raw: bytes, tolerance: int = 300) -> bool:
parts = dict(p.split("=", 1) for p in header.split(",") if "=" in p)
t, v1 = parts.get("t"), parts.get("v1")
if not t or not v1 or not t.isdigit() or abs(time.time() - int(t)) > tolerance:
return False
expected = hmac.new(secret, f"{t}.".encode() + raw, hashlib.sha256).hexdigest()
return hmac.compare_digest(v1, expected)
@asynccontextmanager
async def lifespan(app: FastAPI):
app.state.pool = await asyncpg.create_pool(os.environ["DATABASE_URL"])
yield
await app.state.pool.close()
app = FastAPI(lifespan=lifespan)
@app.post("/hooks/flights", status_code=204)
async def hook(request: Request) -> Response:
raw = await request.body()
if not verify(SECRET, request.headers.get("x-flightbyte-signature", ""), raw):
raise HTTPException(status_code=401)
event = json.loads(raw)
await request.app.state.pool.execute(
"insert into webhook_inbox (event_id, type, body) values ($1, $2, $3) on conflict (event_id) do nothing",
event["id"], event["type"], raw.decode(),
)
return Response(status_code=204)Queue then process
All three endpoints above do the same small thing: verify, insert, answer. The real work happens in a separate loop that reads from the inbox. This is the single most useful pattern for webhook receivers, and it needs nothing more exotic than the database you already have.
create table webhook_inbox (
event_id text primary key,
type text not null,
body jsonb not null,
received_at timestamptz not null default now(),
processed_at timestamptz,
attempts int not null default 0,
last_error text
);The primary key is the deduplication. Workers claim batches with for update skip locked, so several can run without picking the same row:
// worker.ts
import pg from "pg";
import { handle } from "./handle.js"; // your business logic
const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });
async function drain() {
const client = await pool.connect();
try {
await client.query("begin");
const { rows } = await client.query(
`select event_id, body from webhook_inbox
where processed_at is null and attempts < 10
order by received_at
limit 20
for update skip locked`,
);
for (const row of rows) {
try {
await handle(row.body);
await client.query("update webhook_inbox set processed_at = now() where event_id = $1", [row.event_id]);
} catch (err) {
await client.query(
"update webhook_inbox set attempts = attempts + 1, last_error = $2 where event_id = $1",
[row.event_id, String(err)],
);
}
}
await client.query("commit");
} catch (err) {
await client.query("rollback");
throw err;
} finally {
client.release();
}
}
setInterval(() => drain().catch(console.error), 1000);The endpoint's response time no longer depends on your push provider or a slow migration. A bug in handle stops processing but not receiving: events pile up in the table, and when the fix ships the worker catches up without asking the sender for anything. Rows that keep failing stop at ten attempts with the error recorded, a dead-letter queue by another name. SQS, Redis streams or BullMQ work the same way with a different store.
The handler still has to be idempotent
The inbox deduplicates deliveries, but a worker can crash after handle succeeds and before the row is marked processed. Make side effects safe to repeat: upserts instead of inserts, a unique key on the push you send, a check before charging anything.
Common webhook endpoint failures
Most broken endpoints fail in one of a few ways, all of which look alike to the sender: a non-2xx or a timeout.
| Symptom | Usual cause | Fix |
|---|---|---|
| Every delivery fails signature verification | The body was parsed and re-serialized before verifying, or the wrong secret is loaded | Verify the raw bytes; log which secret hint is in use |
Every delivery answers 401 after a deploy | Server clock drifted outside the timestamp window | Run NTP; log the timestamp difference on rejection |
| Timeouts under load | Slow work done before the response | Queue then process |
| The same email sent twice | No deduplication on the event id | Unique key on the id; idempotent side effects |
403 from your own stack | CSRF middleware, an auth guard or a WAF rule applied to the webhook route | Exempt the route; it authenticates by signature |
301 or 308 | HTTP to HTTPS redirect, trailing-slash redirect, or an old domain | Register the final URL exactly |
413 | Body larger than the parser's limit | Raise the limit on the webhook route |
404 after a refactor | The route moved and the registered URL did not | Update the URL with the sender, or keep the old route |
A FlightByte webhook endpoint, end to end
FlightByte delivers flight changes for a subscribed flight to your endpoint. Each delivery is a POST with a JSON body and these headers, documented in full under Webhooks:
POST /hooks/flights HTTP/1.1
Content-Type: application/json
x-flightbyte-event-id: evt_2f0c8a4e-6f1d-4d0d-9a3b-0f1e2d3c4b5a
x-flightbyte-event-type: flight.updated
x-flightbyte-subscription-id: sub_7fd9fa92faf3475db99b
x-flightbyte-delivery-attempt: 1
x-flightbyte-timestamp: 1789305971
x-flightbyte-signature: t=1789305971,v1=5f1c9a...e3b2The body's id is stable across retries, which is what the inbox's primary key relies on. changes lists what moved since the previous delivery, each with a type such as departure.gate.changed, and metadata echoes whatever you stored on the subscription, so one endpoint can serve every booking. The endpoints above work unchanged for it.
When you point a subscription at a new endpoint, two things let you prove it works before any real flight changes. A subscription.created event is delivered right away, and POST /v1/subscriptions/{id}/test sends a subscription.test event through the real signing and delivery path. GET /v1/subscriptions/{id}/deliveries then shows the HTTP status your endpoint returned for each attempt, its latency and any error. A failing endpoint is retried with exponential backoff, and after 20 consecutive failed deliveries the subscription is suspended until you resume it; the retry rules list exactly which responses are retried.
For a complete receiver in context, the flight-landed notification guide builds one in Node.js, and the fan-out guide turns one delivery into a push on every device.
Checked against Stripe, GitHub and Next.js documentation on November 10, 2026.
The quickstart takes a free key to a verified delivery in a few minutes.
Frequently asked questions
What is the difference between a webhook and a webhook endpoint?
A webhook is the event notification: one HTTP request sent when something happens. The webhook endpoint is the URL and the code on your side that receive it. You build and host the endpoint; the sender sends webhooks to it.
Does a webhook endpoint need HTTPS?
Practically, yes. Many senders, Stripe among them, only accept HTTPS URLs for live endpoints, and without TLS the payload and any auth header travel unencrypted. For local development, a tunnel such as ngrok or cloudflared gives you a temporary HTTPS address.
What status code should a webhook endpoint return?
Return a 2xx as soon as the event is durably recorded; 204 No Content is a common choice. Return 401 or 400 for requests you will never accept, such as a bad signature, so the sender does not retry them. Reserve 5xx for failures on your side that a retry could fix.
How fast does a webhook endpoint have to respond?
It depends on the sender, but 10 seconds is a common limit; GitHub and FlightByte both use it. Aim for well under a second by doing only verification and a single insert before responding, and moving everything else to a background worker.
Can one endpoint receive several event types?
Yes, and it usually should. Branch on the event type inside your handler; one endpoint is simpler to secure and monitor than one URL per type.
How do I test a webhook endpoint locally?
Run the endpoint on your machine, expose it with a tunnel, and register the tunnel's URL with the sender. Most senders can also send a test event on demand, and a signed fixture covers unit tests with no network at all.