Webhooks
Your backend receives your app's events (publishes, edits, deletes, reactions…) over HTTP. Push notifications, search indexing, audit logs, and syncing with external systems hook in here.
You configure your webhook URL in the console's webhook screen. On the "Webhook" tab next to your app's overview, enter the address to deliver to (and
before_publishif you need it), and the screen shows you the signing secret once — the console does not store it, so copy it into your endpoint's verification code right away.
Receiving code
import express from 'express'
import { createChatServer } from '@kispi/chat/server'
const app = express()
const seen = new Set<string>() // in production, keep this outside the process (Redis, a table)
const chat = createChatServer({
secretKey: process.env.CHAT_SECRET_KEY!,
webhookSecret: process.env.CHAT_WEBHOOK_SECRET // signing secret the console's webhook screen showed you
})
app.post('/chat-hook', express.raw({ type: 'application/json' }), (req, res) => {
let payload
try {
payload = chat.webhooks.verify(req.headers, req.body.toString('utf8'))
} catch {
return res.sendStatus(400) // signature didn't match. Process nothing
}
const { event, delivery, data } = payload
if (seen.has(delivery)) return res.sendStatus(200) // delivery is at-least-once
seen.add(delivery)
res.sendStatus(200) // respond within 10 seconds first
void handle(event, data) // then process asynchronously
})import hmac, hashlib, json, time
# raw_body is the bytes you received. Parsing and re-serializing breaks the signature.
# Returns the parsed body when the signature matches, or None (-> 400) when it doesn't.
def verify(headers, raw_body, secret):
event = headers.get("X-Chat-Event", "")
delivery = headers.get("X-Chat-Delivery", "") # before_publish has no such header
timestamp, macs = None, []
for item in headers.get("X-Chat-Signature", "").split(","):
name, _, value = item.strip().partition("=")
if name == "t":
timestamp = value
elif name == "v1":
macs.append(value) # there can be several; one match is enough
if timestamp is None or not macs:
return None
if abs(time.time() - int(timestamp)) > 300: # 5 minutes both ways; future stamps are rejected too
return None
signed = f"{timestamp}\n{event}\n{delivery}\n".encode() + raw_body
expected = hmac.new(secret.encode(), signed, hashlib.sha256).hexdigest()
if not any(hmac.compare_digest(expected, mac) for mac in macs):
return None
return json.loads(raw_body)Events you receive
The request body (data) is the content of the event; the event name is in the X-Chat-Event header and the
delivery id in X-Chat-Delivery. chat.webhooks.verify() bundles the three as { event, delivery, data }. Ids
are 13-character strings and times are unix milliseconds.
| Event | When | data |
|---|---|---|
message.created |
A message is stored (thread replies included) | A message object (below) |
message.updated |
A message's text is edited | A message object with editedAt set |
message.deleted |
A message is deleted (by its author, by moderation, or when a user's messages are taken down) | {id, seq} |
reaction.added |
A reaction is pressed | {messageId, emoji, count, userId} — count is that emoji's current count |
reaction.removed |
A reaction is removed | Same as above |
thread.updated |
A reply is added to or removed from a thread root | {rootId, count, lastSeq, lastAt} |
read |
A member's read cursor moves forward | {userId, seq, threadId?} |
member.joined |
A member joins a room | {userId, role} |
member.left |
A member leaves a room | {userId} |
room.updated |
A room's key, name or meta changes |
A room object {id, appId, key?, type, name?, meta, lastSeq, minSeq, createdAt, updatedAt} |
room.deleted |
A room is deleted | {roomId} |
{
"roomId": "0K3M9X2T5Q8RA",
"id": "0K3M9X4B7N1HC",
"appId": "0K3M8Y1P6D5WE",
"seq": 42,
"sender": { "id": "u_42", "name": "Hanna" },
"kind": "text",
"body": { "text": "Hello" },
"clientMsgId": "c_1",
"createdAt": 1760000000000
}A message object also carries, when they apply, replyTo, threadId, mentions (an array of mentioned users'
external ids), meta, appMeta, editedAt and deletedAt, and body can hold attachments and entities.
Reaction and thread aggregates are not included — they arrive separately as reaction.* and thread.updated.
- A room id appears only as
roomIdinmessage.created,message.updatedandroom.deleted, and asidinroom.updated. The payloads of the other events don't carry one. - The console has no setting for choosing which events to receive, so you receive all of the above.
readin particular arrives once for every move of every member's read cursor, which makes it the most frequent event. Filter onX-Chat-Event(orevent) and answer 200 to the ones you don't need. typing,presence,custom,notification.messageanduser.presencearen't stored events, so they are not delivered by webhook.
Four rules
- Verify the raw body as-is. The signature covers the bytes you received, so a string you parsed as
JSON and serialized again won't match. Make sure your framework's JSON parser doesn't consume the body
first by reading this route raw (
express.rawin Express,await request.text()in SvelteKit). - Delivery is at-least-once. The same delivery can arrive twice. Every delivery has a
deliveryid that stays the same across retries — remember the ones you've processed and respond to repeats with just a 200. - Respond with a 2xx within 10 seconds. Taking longer or answering with a non-2xx counts as a failure and starts a backoff (1s → 5s → 25s → 2m → 10m). On failure, that app's deliveries wait at that event and later ones aren't sent ahead of it. If this goes on for over an hour, delivery stops (see "When delivery stops" below). Put heavy work on a queue and respond first.
- Ordering is guaranteed only within a room. Events for a single message (
message.created→reaction.added→message.deleted) never arrive out of order. Events from different rooms can.
When delivery stops
If your endpoint keeps failing for more than an hour from the first failure, the engine stops that app's deliveries. The stop does not clear itself — even after your endpoint recovers, no event is sent until a person resumes delivery. Queued events are not skipped; they stay in the queue.
- The console's Webhook screen for the app shows "Webhook delivery has stopped for this app". Before that, a "Webhook deliveries are behind" warning appears first, and the undelivered count and the age of the oldest event are on the same screen.
- Fix the endpoint first, so it answers 2xx.
- Press Resume delivery in the notice, then Resume in the confirmation dialog. Delivery continues in order from where it stopped.
Catching up on missed events
If your endpoint was down for a while, read past events with chat.events.list({ after, limit }). Each item
is { delivery, event, createdAt, data }, and data is the same as the body the webhook POSTs. Pass the last
delivery you processed as after; an empty cursor means that was everything. Dedupe with delivery here
too — the same event can arrive through both the webhook and this list. Delivered events are kept for 7 days,
so don't put off catching up for longer than that.
This list only accumulates for apps that have a webhook URL set. Whatever happens while no URL is set is not on the list, even if you set a URL later.
before_publish — intercepting before publish
When enabled, publishes and edits pass through your endpoint synchronously. It's the only webhook that can reject a message or return a rewritten body. Profanity filtering, image moderation, and spam blocking live here.
→ { "event": "before_publish", "op": "create" | "update", "messageId"?: "…",
"room": "…", "sender": {…}, "kind": "text", "body": {…}, "meta"?: {…} }
← { "action": "allow" | "deny", "body"?: {…}, "appMeta"?: {…},
"code"?: "…", "message"?: "…" }- You verify it the same way. But since it's a question, it has no
deliveryand isn't subject to deduplication. - On
deny, the sender'ssendfails withmoderation_denied; thecodeyou return lands in the client'serr.appCode, andmessagein the error message. - If you return a
body, the message is stored and broadcast with that instead. The rewritten body goes through the size check again. - If
actionisn'tallowordeny, it counts as a failure, so a typo can't become a moderation bypass. - If your endpoint times out or errors, the default is
allow. You can change it todeny, but then if your endpoint goes down, all publishing for that app stops. - Messages sent through the server API (
sk_) aren't screened.
Keep it fast. The sender's message waits until this call finishes, and the timeout is 1.5 seconds.
Receiving locally
The webhook URL must be https and reachable from the internet. localhost and private IPs are refused.
To receive on a local dev server, start a tunnel such as cloudflared (cloudflared tunnel --url http://localhost:3000) or ngrok
and put the https URL it gives you in the Webhook screen or in Console API PATCH /api/apps/{id}/webhook.
Tunnel URLs can change on every restart, so update it each time.
A tunnel adds hundreds of milliseconds per round trip. With before_publish on, that easily exceeds the 1.5-second timeout, and a
timeout passes as allow by default — if moderation seems to do nothing locally, suspect the tunnel latency first. While testing, set beforePublishOnError to deny so timeouts surface as moderation_denied.
Verifying in another language
Three headers arrive with the request.
| Header | |
|---|---|
X-Chat-Event |
The event name. For before_publish, that value |
X-Chat-Delivery |
The delivery id. before_publish has no such header |
X-Chat-Signature |
t=<unix seconds>,v1=<hex>. The engine sends one v1 today. Write your verifier to read several v1 values and accept on any one match |
The signing input is four pieces joined with newlines (\n).
<t>
<X-Chat-Event>
<X-Chat-Delivery, or an empty string>
<the raw body bytes you received>v1 is hex(HMAC-SHA256(webhook secret, signing input)). The secret is not your sk_: it's the separate
webhook secret shown once on the console's webhook screen. Reject the delivery if the absolute value of
now - t is more than 5 minutes (both directions — a future timestamp is rejected too). Retries refresh
t but keep X-Chat-Delivery, so dedupe on that value.
Rotating the secret
Press Rotate secret on the app's Webhook screen in the console and confirm; the new webhook secret is shown there once.
There is no overlap between the old secret and the new one. Every delivery is signed with a single secret (one
v1), so from the moment you rotate, all deliveries are signed with the new secret — queued events and events
being retried included — and the old secret no longer verifies.
- Press Rotate secret and copy the new secret.
- Put it in your endpoint's webhook secret (for example
CHAT_WEBHOOK_SECRET) and deploy right away. - Deliveries that arrive before the deploy finishes fail signature verification, are recorded as failures, and come back on the backoff. If you deploy within an hour, no event is lost. If it takes longer and delivery has stopped, press Resume delivery on the Webhook screen.