---
source_url: https://www.pubnub.com/docs/serverless/functions/functions-apis/ugc-module
title: UGC Moderate Message
updated_at: 2026-05-22T11:08:29.186Z
---

> Documentation Index
> For a curated overview of PubNub documentation, see: https://www.pubnub.com/docs/llms.txt
> For the full list of all documentation pages, see: https://www.pubnub.com/docs/llms-full.txt


# UGC Moderate Message

:::note Beta feature
Auto Moderation is in **beta** and available upon request. Contact [PubNub Support](https://www.pubnub.com/docs/mailto:support@pubnub.com) or [Sales](https://www.pubnub.com/company/contact-sales/).
:::

:::note UGC API availability
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](https://www.pubnub.com/docs/bizops-workspace/auto-moderation) for setup details.
:::

:::tip Related moderation approaches
The UGC module allows custom implementation of Auto Moderation logic in your Functions. For easier setup without custom code, use [Auto Moderation](https://www.pubnub.com/docs/bizops-workspace/auto-moderation) in BizOps Workspace. For manual moderation, see [Channel Monitor](https://www.pubnub.com/docs/bizops-workspace/channel-monitor). For a complete overview of all moderation options, see the [Moderation Overview](https://www.pubnub.com/docs/general/moderation/overview).
:::

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](https://www.pubnub.com/docs/bizops-workspace/auto-moderation). 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](https://www.pubnub.com/docs/bizops-workspace/auto-moderation#auto-moderation-with-an-existing-before-publish-function).

For setup details and dependencies, see [Auto Moderation](#auto-moderation). Once Auto Moderation is configured, import the UGC module as shown below.

## Import

```javascript
const ugc = require('ugc');
```

## API

Use the following signature to call the API.

```typescript
function 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](https://www.npmjs.com/package/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:

```javascript
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`:

```javascript
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');
    }
    if (res.transform?.meta) request.params.meta = JSON.stringify(res.transform.meta);
    if (res.transform?.message) request.message = res.transform.message;
    return request.ok();
  }).catch((err) => {
    console.log('Moderation error:', err);
    return request.ok();
  });
};
```

## Example responses

Unflagged content:

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

Flagged content (mask and block):

```json
{
  "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)

| 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.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](https://www.pubnub.com/docs/bizops-workspace/auto-moderation#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.

:::warning 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`.

## Terms in this document

* **PubNub** - PubNub is a real-time messaging platform that provides APIs and SDKs for building scalable applications. It handles the complex infrastructure of real-time communication, including: Message delivery and persistence, Presence detection, Access control, Push notifications, File sharing, Serverless processing with Functions and Events & Actions, Analytics and monitoring with BizOps Workspace, AI-powered insights with Illuminate.
