Guide

How to Add Content Moderation to a Chat SDK (Stream, CometChat, PubNub, Twilio, Sendbird)

·11 min read

Most chat SDKs (Stream, CometChat, PubNub, Twilio Conversations, Sendbird) store and deliver messages on their servers, not yours. To filter a message before anyone else sees it, you need the SDK's pre-send hook: a server-side callback that runs between "user hit send" and "message delivered", where your code can approve, rewrite or reject it.

This guide shows the hook each SDK provides, what it expects back, how long you have, and what happens when you're too slow. Then it gives you one moderation handler to plug into any of them.

The pattern

  1. The chat SDK calls your endpoint (or runs your function) with the pending message.
  2. Your code sends the text to a moderation API and gets back a decision.
  3. You translate that decision into the SDK's response format: deliver, rewrite or block.
  4. You log the decision ID next to the message ID, so you can explain the decision later.

Every SDK below gives you a strict time budget. Your moderation call needs its own timeout, set well under the SDK's.

Pre-send hooks by SDK

SDKHookHow to blockHow to rewriteTime limitWhen your hook fails
Stream ChatBefore Message Send webhookReturn the message with type: "error" (HTTP 200)Return the edited message1.5 s per attempt by default (configurable 1–5000 ms)Fails open: the message is stored
CometChatModeration rule with a Custom API conditionReturn isMatchingCondition: true with confidence at or above your threshold; the rule's block action runsNot via this hook2 sConfigurable: "Approve Message" (default) or "Block Message"
PubNubFunction, "Before Publish or Fire"request.abort()Edit request.message, then request.ok()Function execution limits applyFails closed on Functions infrastructure failure
Twilio ConversationsPre-action webhook onMessageAddRespond with any 4xx/5xxRespond 200 with a new body and/or attributes5 sFails open: published unmodified after the timeout
SendbirdBuilt-in profanity, domain and image filtersConfigured in SendbirdAsterisk replacement in the profanity filtern/an/a. No documented pre-send hook for your own code.

Sources: Stream, CometChat, PubNub, Twilio, Sendbird. Checked November 2026. Vendors change these, so confirm the limits for your plan.

One moderation function for every SDK

Keep the moderation call in one place and give it a hard timeout. This version returns null when moderation couldn't finish, so each SDK adapter can decide whether that means deliver or hold.

lib/moderate-message.tsTypeScript
type Verdict = { action: 'allow' | 'warn' | 'flag' | 'block'; decisionId: string };
export async function moderateMessage(
text: string,
meta: { userId: string; channelId: string },
timeoutMs = 700, // keep well under the SDK's hook timeout
): Promise<Verdict | null> {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeoutMs);
try {
const res = await fetch('https://api.vettly.dev/v1/check', {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.VETTLY_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
content: text,
contentType: 'text',
policyId: process.env.VETTLY_POLICY_ID,
metadata: meta,
}),
signal: controller.signal,
});
if (!res.ok) return null;
const { action, decisionId } = await res.json();
return { action, decisionId };
} catch {
return null; // timeout or network error
} finally {
clearTimeout(timer);
}
}

action comes back as allow, warn, flag or block. In chat, a common mapping:

  • allow: deliver.
  • warn: deliver, and optionally nudge the sender.
  • flag: deliver, or hide from others until reviewed (your choice), and add it to a review queue.
  • block: reject, and tell the sender why.

Stream Chat

Enable the Before Message Send hook in your app settings and point it at your endpoint. Stream posts the message. To let it through, return the message (edited or not). To block it, return it with type: "error" and the text the sender should see. Always respond with HTTP 200.

routes/stream-before-send.tsNode.js
app.post('/hooks/stream/before-send', async (req, res) => {
// Verify Stream's webhook signature here before trusting the body.
const { message, user, channel_id } = req.body;
const verdict = await moderateMessage(message.text ?? '', {
userId: user?.id, channelId: channel_id,
});
if (verdict?.action === 'block') {
return res.json({
message: { ...message, type: 'error', text: 'This message was not sent because it breaks the community rules.' },
});
}
// null (timeout) falls through: Stream would fail open anyway,
// so re-check this message asynchronously and remove it if needed.
if (!verdict) await recheckQueue.add({ messageId: message.id });
return res.json({ message });
});

Stream fails open, so a slow handler means the message goes out unchecked. The re-check queue closes that gap: moderate those messages a few seconds later and hard-delete any that come back block.

CometChat

CometChat's moderation engine can call your own API as a rule condition. You don't send back a verdict. You answer "does this message match the condition?" with a confidence score, and the rule's configured action (block or flag) does the rest.

routes/cometchat-condition.tsNode.js
app.post('/hooks/cometchat/condition', async (req, res) => {
// Body includes the message (and earlier context messages).
const text = req.body?.message?.data?.text ?? '';
const verdict = await moderateMessage(text, {
userId: req.body?.message?.sender, channelId: req.body?.message?.receiver,
});
if (!verdict) return res.status(503).end(); // triggers "On Custom API Error"
const matches = verdict.action === 'block' || verdict.action === 'flag';
return res.json({
isMatchingCondition: matches,
confidence: matches ? 1 : 0,
reason: matches ? `Vettly decision ${verdict.decisionId}` : undefined,
});
});

Check the exact payload fields in your CometChat dashboard's test tool before relying on the paths above. Set On Custom API Error to "Block Message" if you'd rather hold messages than deliver them unchecked.

PubNub

PubNub runs your code inside its Functions runtime, with a "Before Publish or Fire" trigger on the channels you choose. Call the moderation API with PubNub's xhr module, then abort() to drop the message or ok() to deliver it.

functions/moderate.jsJavaScript
export default async (request) => {
const xhr = require('xhr');
const vault = require('vault');
const apiKey = await vault.get('VETTLY_API_KEY');
const policyId = await vault.get('VETTLY_POLICY_ID');
try {
const res = await xhr.fetch('https://api.vettly.dev/v1/check', {
method: 'POST',
headers: { Authorization: 'Bearer ' + apiKey, 'Content-Type': 'application/json' },
body: JSON.stringify({ content: request.message.text, contentType: 'text', policyId }),
});
const verdict = JSON.parse(res.body);
if (verdict.action === 'block') return request.abort();
request.message.moderation = { action: verdict.action, decisionId: verdict.decisionId };
return request.ok();
} catch (e) {
return request.ok(); // or request.abort() to fail closed
}
};

Annotating the message with the decision ID lets clients hide flag messages, and gives you an audit link back to the decision.

Twilio Conversations

Configure a pre-action webhook for onMessageAdd. Twilio waits for your response: a 4xx or 5xx rejects the message, and a 200 with a body replaces the text.

routes/twilio-on-message-add.tsNode.js
app.post('/hooks/twilio/conversations', express.urlencoded({ extended: false }), async (req, res) => {
// Validate the X-Twilio-Signature header first.
if (req.body.EventType !== 'onMessageAdd') return res.status(200).json({});
const verdict = await moderateMessage(req.body.Body ?? '', {
userId: req.body.Author, channelId: req.body.ConversationSid,
});
if (verdict?.action === 'block') return res.status(403).end();
return res.status(200).json({}); // publish unchanged
});

Twilio publishes the message unmodified if you take longer than 5 seconds. Also note that Twilio's docs currently label this webhook API "Conversations (classic)".

Sendbird

Sendbird's moderation features run on Sendbird's side: keyword and regex profanity filters, domain filters, penalties such as mute or ban for repeat offenders, and image moderation. You configure them through the dashboard or Platform API. We found no documented hook that lets your code approve or block a message before delivery.

If you need your own policy (multilingual abuse, scams, context-aware harassment), you have two realistic options:

  • Send through your backend. Clients call your API, you moderate, then you post the message with the Sendbird Platform API. You get full control, at the cost of one extra hop.
  • Moderate after delivery. Subscribe to message webhooks, check each message, and delete or hide anything that comes back block. The message is visible briefly.

Things that bite in production

  • Verify the webhook signature. Every one of these endpoints is public. Check the vendor's signature header before you trust the body.
  • Edits are a second chance to slip something past you. Moderate message updates as well as new messages, where the SDK lets you.
  • Attachments skip text checks. Send image URLs through an image check (contentType: 'image') separately, and accept that image checks are slower than the hook budget for some SDKs.
  • Log the decision ID with the message ID. When a user appeals, or a regulator asks, you need to show what was decided and why.
  • Different rooms, different policies. Use separate policy IDs for children's rooms and adult rooms rather than one compromise threshold.

Related: Real-time moderation latency · Live chat moderation API · Game chat moderation

Plug Vettly into your chat hook

One REST call returns allow, warn, flag or block, with a decision ID you can store next to the message. It works the same behind Stream, CometChat, PubNub or Twilio.

Frequently asked questions

How do I filter messages in a chat SDK before other users see them?

Use the SDK's server-side pre-send hook: Stream's Before Message Send webhook, CometChat's Custom API moderation rule, PubNub's Before Publish or Fire function, or Twilio Conversations' onMessageAdd pre-action webhook. The hook sends your server the message, you call a moderation API, and your response tells the SDK to deliver, rewrite or block it.

Does Sendbird have a pre-send moderation webhook?

We couldn't find a documented server-side hook that lets your code block a Sendbird message before delivery. Sendbird has its own profanity, domain and image filters configured on its side, and a profanity_filter:block webhook that fires after a block. If you need your own policy, the usual pattern is to send messages through your backend with the Platform API and moderate there.

Should a chat moderation hook fail open or closed?

It depends on the audience. Stream, CometChat (by default) and Twilio deliver the message if your hook is slow or errors. PubNub's Before Publish functions fail closed on a Functions infrastructure failure. For adult social chat, failing open with an after-the-fact check is common. For children's chat, prefer the CometChat 'Block Message' setting or a design where messages are held until checked.

How fast does the moderation call need to be?

Faster than the hook timeout, with room to spare. Stream defaults to 1.5 seconds per attempt, CometChat allows 2 seconds and Twilio 5 seconds. Set your own HTTP timeout to roughly half the vendor's limit, so your handler can still return a clear decision when the moderation call is slow.