UGC Moderate Message
Beta feature
Auto Moderation is in beta and available upon request. Test in a development environment before production. To get access, contact PubNub Support or Sales.
The ugc.moderateMessage API isn’t gated. It relies on a PubNub Auto Moderation configuration (configId) created in BizOps Workspace. Ensure Auto Moderation is enabled on your account and a configuration is set up. See the Auto Moderation Configuration Guide for setup details.
Use ugc.moderateMessage to moderate user‑generated content in your PubNub Function. The API calls an internal service and returns clear results so you can block, mask, or handle content before publish.
Add moderation with a single API call in your Function. You can mask words or detect spam quickly.
To edit or block before publish, use a Before Publish or Fire Function. You can also call this API in other Function types if your channel topology calls for it.
This is useful when you already run a Before Publish or Fire Function on a channel. Each channel supports one Function of this type. You won’t add a separate automatic Auto Moderation Function. Define the moderation behavior in your Auto Moderation configuration and call ugc.moderateMessage in your current Function.
To use this module, provide configId—the UUID of the Auto Moderation configuration you create in BizOps Workspace’s Auto Moderation.
For setup details and dependencies, see Auto Moderation. Once Auto Moderation is configured, import the UGC module as shown below.
Import
1const ugc = require('ugc');
API
Use the following signature to call the API.
1function moderateMessage(req: ModerateMessageRequest): Promise<ModerateMessageResponse>
Input
Provide a ModerateMessageRequest object with the following fields:
| Field | Type | Required | Description |
|---|---|---|---|
configId | string | Yes | UUID of your Auto Moderation configuration, created in BizOps Workspace (for example, uuidv4). |
message | JSON | Yes | Full publish body. Policies read the top‑level text field by default (configurable). Send the complete payload. |
channel | string | Yes | Channel that receives the message. |
userId | string | Yes | User ID (the uuid parameter) of the publisher. |
meta | JSON | No | Optional metadata with custom key‑value pairs. PubNub Functions receive this as stringified JSON. Parse before use, for example: JSON.parse(request.params.meta). |
Output
The call returns a ModerateMessageResponse object with these fields:
| Field | Type | Required | Description |
|---|---|---|---|
moderationId | string | Yes | Unique ID for auditing and correlation. |
flagged | boolean | Yes | True if any moderation rule was triggered. |
actions | string[] | Yes | Actions to take (configuration‑defined), for example: ["block", "mask"/"wordMasked", "report"]. |
categories | Record<string, CategoryResult> | Yes | Per-category results returned as structured CategoryResult objects. |
transform | object | No | Suggested changes to apply. May be an empty object when no changes are needed. |
→ message | JSON | No | Message with masks/edits applied. |
→ meta | JSON | No | Meta augmented with moderation fields (for example, report identifiers). |
CategoryResult
| Field | Type | Required | Description |
|---|---|---|---|
flagged | boolean | Yes | Whether this category triggered. |
details | object | No | Category-specific details. |
→ maskedWords | string[] | No | Present for word-list violations. |
Example:
1const spam = response.categories.spam; // CategoryResult
2const isSpam = spam?.flagged === true;
Usage
The following example shows how to use the result in a Before Publish or Fire Function:
1export default (request) => {
2 const ugc = require('ugc');
3
4 const metaFromClient = typeof request.params.meta === 'string' ? JSON.parse(request.params.meta) : request.params.meta;
5
6 return ugc.moderateMessage({
7 configId: '<YOUR_MODERATION_CONFIG_ID>', // Moderation config ID (generated by Auto Moderation), like a088649f-cf9d-451c-b6c3-abc1908fc03a
8 message: request.message, // message body from the publish
9 userId: request.params.uuid, // publish UUID set by the client
10 channel: request.channels[0], // channel the message is being published to
11 meta: metaFromClient, // Functions passes meta as a string; parse to JSON before sending
12 }).then((res) => {
13 if (res.flagged && res.actions.includes('block')) {
14 request.status = 403;
15 return request.abort('Flagged');
show all 24 linesExample responses
Unflagged content:
1{
2 "moderationId": "c3b0...",
3 "flagged": false,
4 "actions": [],
5 "categories": { "spam": { "flagged": false }}
6}
Flagged content (mask and block):
1{
2 "moderationId": "a1f2...",
3 "flagged": true,
4 "actions": ["block", "wordMasked"],
5 "categories": {
6 "spam": { "flagged": true },
7 "wordMasking": { "flagged": true, "details": { "maskedWords": ["word"] } }
8 },
9 "transform": {
10 "message": { "text": "spam spam ****" },
11 "meta": { "reportTimetoken": "17551044120707427" }
12 }
13}
Validation and errors
The tables below summarize input validation rules. They also show how service and network errors are handled.
Validation (inputs)
| Field | Condition | Error message |
|---|---|---|
configId | Missing | configId must be provided |
message | Undefined or null | message must be provided |
channel | Missing or not a string | channel must be provided and must be a string |
userId | Missing or not a string | userId must be provided and must be a string |
Errors (service and transport)
| Scenario | Behavior/Result | Notes |
|---|---|---|
| Moderation API non-2xx | Promise resolves with parsed error body when available (for example, error) | Built-in retries (default 3) |
| Network/transport failure | Promise rejects | Counts toward XHR-per-execution |
Behavior and limits
These characteristics apply when you call ugc.moderateMessage() from a Function:
- Your moderation policy lives in your Auto Moderation configuration. Update policy without changing your code; keep the same
configId. - Transport retries: 3 attempts by default.
- Each call counts as one XHR toward the per‑execution total (default limit: 5).
Auto Moderation
The ugc.moderateMessage module and PubNub Auto Moderation use the same backend and pre‑provisioned configurations (identified by configId). This keeps decisions, actions, and audit IDs consistent.
When to choose which approach:
- Use the
ugc.moderateMessagemodule when you already have aBefore Publish or FireFunction and want to evaluate moderation and take action in that same Function with a single call. Read the Auto Moderation with an existing Before Publish Function guide for detailed steps. - Use PubNub Auto Moderation when you want PubNub to run a dedicated moderation Function for you.
Before Publish or Fire constraint
Each channel supports one Before Publish or Fire Function per keyset. Consolidate pre‑publish logic, including moderation, into this Function for best performance.
Migration and edge cases:
- If you use PubNub Auto Moderation and need custom logic, consolidate into a single
Before Publish or Fire Functionthat callsugc.moderateMessage. Ask BizOps to disable the managed Function on those channels. - If you need extra processing that does not have to block messages, add an
After Publish or Fire Functionfor post‑processing. It cannot block or modify the message before delivery.
Best practices
These tips help you implement moderation predictably and keep your Function future‑proof:
- Check
response.actionsto enforce block or mask before publish. - Apply
response.transformwhen present to keep masking and reporting consistent. - Parse
request.params.metabefore sending; stringify when assigning back torequest.params.metaafter transforms. - For category‑specific behavior, check
response.categories["<name>"].flagged.