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

const ugc = require('ugc');

API

Use the following signature to call the API.

function moderateMessage(req: ModerateMessageRequest): Promise<ModerateMessageResponse>

Input

Provide a ModerateMessageRequest object with the following fields:

FieldTypeRequiredDescription
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:

FieldTypeRequiredDescription
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

FieldTypeRequiredDescription
flagged
boolean
Yes
Whether this category triggered.
details
object
No
Category-specific details.
→ maskedWords
string[]
No
Present for word-list violations.

Example:

const spam = response.categories.spam; // CategoryResult
const isSpam = spam?.flagged === true;

Usage

The following example shows how to use the result in a Before Publish or Fire Function:

export default (request) => {
const ugc = require('ugc');

const metaFromClient = typeof request.params.meta === 'string' ? JSON.parse(request.params.meta) : request.params.meta;

return ugc.moderateMessage({
configId: '<YOUR_MODERATION_CONFIG_ID>', // Moderation config ID (generated by Auto Moderation), like a088649f-cf9d-451c-b6c3-abc1908fc03a
message: request.message, // message body from the publish
userId: request.params.uuid, // publish UUID set by the client
channel: request.channels[0], // channel the message is being published to
meta: metaFromClient, // Functions passes meta as a string; parse to JSON before sending
}).then((res) => {
if (res.flagged && res.actions.includes('block')) {
request.status = 403;
return request.abort('Flagged');
show all 24 lines

Example responses

Unflagged content:

{
"moderationId": "c3b0...",
"flagged": false,
"actions": [],
"categories": { "spam": { "flagged": false }}
}

Flagged content (mask and block):

{
"moderationId": "a1f2...",
"flagged": true,
"actions": ["block", "wordMasked"],
"categories": {
"spam": { "flagged": true },
"wordMasking": { "flagged": true, "details": { "maskedWords": ["word"] } }
},
"transform": {
"message": { "text": "spam spam ****" },
"meta": { "reportTimetoken": "17551044120707427" }
}
}

Validation and errors

The tables below summarize input validation rules. They also show how service and network errors are handled.

Validation (inputs)

FieldConditionError 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)

ScenarioBehavior/ResultNotes
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.moderateMessage module when you already have a Before Publish or Fire Function 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 Function that calls ugc.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 Function for 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.actions to enforce block or mask before publish.
  • Apply response.transform when present to keep masking and reporting consistent.
  • Parse request.params.meta before sending; stringify when assigning back to request.params.meta after transforms.
  • For category‑specific behavior, check response.categories["<name>"].flagged.
Last updated on