The official TypeScript and JavaScript library for Moderation API. Use it on the server to moderate text, images, video and audio, manage authors, review queues, actions and wordlists, and verify webhooks.
- Get an API key in the dashboard.
- Read the documentation and the API reference.
Warning
Keep your API key secret. Use this SDK on your server, not in a browser or mobile app, where users can read the key.
Moderation API: Moderate text, images, video and audio in real time, manage authors, review queues and actions, and receive webhooks.
More information about the API can be found at https://docs.moderationapi.com
The SDK can be installed with either npm, pnpm, bun or yarn package managers.
npm add @moderation-api/sdkpnpm add @moderation-api/sdkbun add @moderation-api/sdkyarn add @moderation-api/sdkNote
This package is published with CommonJS and ES Modules (ESM) support.
For supported JavaScript runtimes, please consult RUNTIMES.md.
import { ModerationApi } from "@moderation-api/sdk";
const moderationApi = new ModerationApi({
secretKey: process.env["MODAPI_SECRET_KEY"] ?? "",
});
async function run() {
const result = await moderationApi.content.submit({
content: {
type: "text",
text: "Hey, check out my profile for a deal!",
},
contentId: "message-48213",
authorId: "user-1092",
conversationId: "room-general",
metadata: {
"platform": "ios",
},
});
console.log(result);
}
run();Use content.submit to moderate text, images, video, audio, or objects with several fields. All parameters except content are optional.
The client reads your API key from the MODAPI_SECRET_KEY environment variable. To set it in code, pass secretKey.
import { ModerationApi } from "@moderation-api/sdk";
const moderationApi = new ModerationApi(); // reads MODAPI_SECRET_KEY
// Text
await moderationApi.content.submit({
content: { type: "text", text: "Your text here" },
contentId: "message-123", // your ID for the content
authorId: "user-123", // your ID for the user who wrote it
conversationId: "room-123", // groups related content
metadata: { platform: "ios" },
});
// Image, video and audio: send a URL
await moderationApi.content.submit({
content: { type: "image", url: "https://example.com/image.jpg" },
});
await moderationApi.content.submit({
content: { type: "video", url: "https://example.com/video.mp4" },
});
await moderationApi.content.submit({
content: { type: "audio", url: "https://example.com/audio.mp3" },
});
// An object with several fields, moderated together
await moderationApi.content.submit({
content: {
type: "object",
data: {
title: { type: "text", text: "Post title" },
body: { type: "text", text: "Post content" },
thumbnail: { type: "image", url: "https://example.com/thumb.jpg" },
},
},
});evaluation.flagged tells you if any policy flagged the content. recommendation.action is the action the API recommends after it applies your thresholds and rules: allow, review or reject.
const result = await moderationApi.content.submit({
content: { type: "text", text: "Some content" },
});
if (result.evaluation.flagged) {
console.log("A policy flagged the content");
}
switch (result.recommendation.action) {
case "reject":
// Block the content
break;
case "allow":
// Publish the content
break;
case "review":
default:
// Publish or hold it, and send it to a review queue.
// `default` also catches actions added to the API later.
break;
}
for (const policy of result.policies) {
if ("id" in policy) {
console.log(`${policy.id}: flagged=${policy.flagged}`);
}
}Some fields are open enums, for example recommendation.action and the error code. The API can add a value, and an older SDK version then returns it as a plain string. It does not throw. Always handle unknown values: for recommendation.action, treat an unknown value as review, as the default branch above does.
Moderation API signs every webhook delivery with your project's webhook signing secret. The signature is in the modapi-signature header.
Find the secret on the API keys page in the dashboard, or get it with await moderationApi.webhookSecret.retrieve(). Store it in the MODAPI_WEBHOOK_SECRET environment variable. It is not your API key. Get it once, for example in a setup script, and do not call retrieve for each delivery, so verification does not depend on a call to the API. Keep it as secret as your API key: anyone with it can sign webhooks.
validateWebhook checks the signature against the raw body and returns the event. It does not need a client. It reads the secret from MODAPI_WEBHOOK_SECRET; to set it in code, pass secret. It throws WebhookSignatureError if the signature does not match.
Verification needs the raw body, byte for byte. If your framework parses the JSON body first and you serialize it again, the bytes can change and the check fails.
Fetch API (Next.js App Router, Hono, Bun, Cloudflare Workers):
import { validateWebhook } from "@moderation-api/sdk";
export async function POST(request: Request) {
try {
const event = await validateWebhook({ request });
console.log(event.type);
} catch {
return new Response("Invalid signature", { status: 400 });
}
return new Response(null, { status: 200 });
}Express: use express.raw on the webhook route, so req.body is the raw body.
import express from "express";
import { validateWebhook } from "@moderation-api/sdk";
const app = express();
app.post(
"/webhooks/moderation",
express.raw({ type: "application/json" }),
async (req, res) => {
try {
const event = await validateWebhook({ request: req });
console.log(event.type);
res.sendStatus(200);
} catch {
res.sendStatus(400);
}
},
);Next.js Pages Router: turn off the body parser for the route. validateWebhook then reads the raw body from the request.
import type { NextApiRequest, NextApiResponse } from "next";
import { validateWebhook } from "@moderation-api/sdk";
export const config = { api: { bodyParser: false } };
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
try {
const event = await validateWebhook({ request: req });
console.log(event.type);
res.status(200).end();
} catch {
res.status(400).end();
}
}validateWebhook returns a WebhookEvent, a union of the event types. Switch on event.type and TypeScript knows the shape of event.data.object. Each event also has its own type, for example QueueItemRejectedEvent or AuthorBlockedEvent.
Webhook payloads use the API's field names, in snake_case (flagged_fields, external_id). The request and response objects of the client methods use camelCase (flaggedFields, externalId).
The payload is not validated against a schema, so a field or an event type added to the API later never fails a delivery. An event type that this SDK version does not know reaches the default branch. Read it as UnknownWebhookEvent.
import { validateWebhook, type UnknownWebhookEvent } from "@moderation-api/sdk";
const event = await validateWebhook({ request });
switch (event.type) {
case "queue_item.rejected": {
const { item, author } = event.data.object;
console.log(item?.id, item?.flagged_fields, author?.external_id);
break;
}
case "author.blocked": {
console.log(event.data.object.author.external_id);
break;
}
default: {
const unknown = event as UnknownWebhookEvent;
console.log(`Unhandled event ${unknown.type}`);
}
}This SDK supports the following security scheme globally:
| Name | Type | Scheme | Environment Variable |
|---|---|---|---|
secretKey |
http | HTTP Bearer | MODAPI_SECRET_KEY |
To authenticate with the API the secretKey parameter must be set when initializing the SDK client instance. For example:
import { ModerationApi } from "@moderation-api/sdk";
const moderationApi = new ModerationApi({
secretKey: process.env["MODAPI_SECRET_KEY"] ?? "",
});
async function run() {
const result = await moderationApi.analytics.summary();
console.log(result);
}
run();Moderation API has two kinds of API keys:
- A project key works with one project: content, authors, review queues, actions, wordlists, webhooks and the account. Most integrations need only this key.
- An organization key works with the management API: projects and channels. It can also use any project's endpoints: name the project with
projectId.
A project key can't call the management API: the API returns 403 with the code organization_key_required. If you use both kinds of key, create one client for each:
import { ModerationApi } from "@moderation-api/sdk";
// Project key, from MODAPI_SECRET_KEY
const moderationApi = new ModerationApi();
// Organization key
const managementApi = new ModerationApi({
secretKey: process.env["MODAPI_ORGANIZATION_KEY"] ?? "",
});
for await (const page of await managementApi.projects.list()) {
for (const project of page.result.data) {
console.log(project.id, project.name);
}
}Create the organization client only where you manage projects and channels, for example in a setup script, and keep the organization key out of the code that moderates content.
Available methods
- retrieve - Get account details
- list - List moderation actions
- create - Create an action
- retrieve - Get an action
- update - Update an action
- delete - Delete an action
- execute - Execute moderation action
- summary - Get the analytics summary
- policies - Get the most flagged policies
- authors - Get the most flagged authors
- channels - Get analytics per channel
- volumes - Get volumes over time
- automation - Get the automation breakdown
- list - List authors
- create - Create a new author
- retrieve - Get author details
- update - Update author details
- delete - Delete an author
- list - List channels
- create - Create a channel
- retrieve - Get a channel
- update - Update a channel
- delete - Delete a channel
- duplicate - Duplicate a channel
- submit - Submit content
- create - Send feedback
- list - List projects
- create - Create a project
- retrieve - Get a project
- update - Update a project
- delete - Delete a project
- duplicate - Duplicate a project
- create - Create a project API key
- list - List queue items
- resolve - Resolve a queue item
- resolveMany - Resolve queue items
- unresolve - Unresolve a queue item
- list - List webhooks
- create - Create a webhook
- retrieve - Get a webhook
- update - Update a webhook
- delete - Delete a webhook
- retrieve - Get the webhook signing secret
- list - List wordlists
- create - Create wordlist
- retrieve - Get wordlist
- update - Update wordlist
- getEmbeddingStatus - Get embedding status
All the methods listed above are available as standalone functions. These functions are ideal for use in applications running in the browser, serverless runtimes or other environments where application bundle size is a primary concern. When using a bundler to build your application, all unused functionality will be either excluded from the final bundle or tree-shaken away.
To read more about standalone functions, check FUNCTIONS.md.
Available standalone functions
accountRetrieve- Get account detailsactionsCreate- Create an actionactionsDelete- Delete an actionactionsExecute- Execute moderation actionactionsList- List moderation actionsactionsRetrieve- Get an actionactionsUpdate- Update an actionanalyticsAuthors- Get the most flagged authorsanalyticsAutomation- Get the automation breakdownanalyticsChannels- Get analytics per channelanalyticsPolicies- Get the most flagged policiesanalyticsSummary- Get the analytics summaryanalyticsVolumes- Get volumes over timeauthorsCreate- Create a new authorauthorsDelete- Delete an authorauthorsList- List authorsauthorsRetrieve- Get author detailsauthorsUpdate- Update author detailschannelsCreate- Create a channelchannelsDelete- Delete a channelchannelsDuplicate- Duplicate a channelchannelsList- List channelschannelsRetrieve- Get a channelchannelsUpdate- Update a channelcontentSubmit- Submit contentfeedbackCreate- Send feedbackprojectsApiKeysCreate- Create a project API keyprojectsCreate- Create a projectprojectsDelete- Delete a projectprojectsDuplicate- Duplicate a projectprojectsList- List projectsprojectsRetrieve- Get a projectprojectsUpdate- Update a projectqueueGetStats- Get queue statisticsqueueItemsList- List queue itemsqueueItemsResolve- Resolve a queue itemqueueItemsResolveMany- Resolve queue itemsqueueItemsUnresolve- Unresolve a queue itemqueueList- List queuesqueueRetrieve- Get a queuewebhooksCreate- Create a webhookwebhooksDelete- Delete a webhookwebhookSecretRetrieve- Get the webhook signing secretwebhooksList- List webhookswebhooksRetrieve- Get a webhookwebhooksUpdate- Update a webhookwordlistCreate- Create wordlistwordlistGetEmbeddingStatus- Get embedding statuswordlistList- List wordlistswordlistRetrieve- Get wordlistwordlistUpdate- Update wordlistwordlistWordsAdd- Add words to wordlistwordlistWordsRemove- Remove words from wordlist
Some of the endpoints in this SDK support pagination. To use pagination, you
make your SDK calls as usual, but the returned response object will also be an
async iterable that can be consumed using the for await...of
syntax.
Here's an example of one such pagination call:
import { ModerationApi } from "@moderation-api/sdk";
const moderationApi = new ModerationApi({
secretKey: process.env["MODAPI_SECRET_KEY"] ?? "",
});
async function run() {
const result = await moderationApi.authors.list({});
for await (const page of result) {
console.log(page);
}
}
run();Some of the endpoints in this SDK support retries. If you use the SDK without any configuration, it will fall back to the default retry strategy provided by the API. However, the default retry strategy can be overridden on a per-operation basis, or across the entire SDK.
To change the default retry strategy for a single API call, simply provide a retryConfig object to the call:
import { ModerationApi } from "@moderation-api/sdk";
const moderationApi = new ModerationApi({
secretKey: process.env["MODAPI_SECRET_KEY"] ?? "",
});
async function run() {
const result = await moderationApi.analytics.summary(
undefined,
undefined,
undefined,
{
retries: {
strategy: "backoff",
backoff: {
initialInterval: 1,
maxInterval: 50,
exponent: 1.1,
maxElapsedTime: 100,
},
retryConnectionErrors: false,
},
},
);
console.log(result);
}
run();If you'd like to override the default retry strategy for all operations that support retries, you can provide a retryConfig at SDK initialization:
import { ModerationApi } from "@moderation-api/sdk";
const moderationApi = new ModerationApi({
retryConfig: {
strategy: "backoff",
backoff: {
initialInterval: 1,
maxInterval: 50,
exponent: 1.1,
maxElapsedTime: 100,
},
retryConnectionErrors: false,
},
secretKey: process.env["MODAPI_SECRET_KEY"] ?? "",
});
async function run() {
const result = await moderationApi.analytics.summary();
console.log(result);
}
run();ModerationAPIError is the base class for all HTTP error responses. It has the following properties:
| Property | Type | Description |
|---|---|---|
error.message |
string |
Error message |
error.statusCode |
number |
HTTP response status code eg 404 |
error.headers |
Headers |
HTTP response headers |
error.body |
string |
HTTP body. Can be empty string if no body is returned. |
error.rawResponse |
Response |
Raw HTTP response |
error.data$ |
Optional. Some errors may contain structured data. See Error Classes. |
import { ModerationApi } from "@moderation-api/sdk";
import * as errors from "@moderation-api/sdk/models/errors";
const moderationApi = new ModerationApi({
secretKey: process.env["MODAPI_SECRET_KEY"] ?? "",
});
async function run() {
try {
const result = await moderationApi.analytics.summary();
console.log(result);
} catch (error) {
// The base class for HTTP error responses
if (error instanceof errors.ModerationAPIError) {
console.log(error.message);
console.log(error.statusCode);
console.log(error.body);
console.log(error.headers);
// Depending on the method different errors may be thrown
if (error instanceof errors.BadRequestError) {
console.log(error.data$.type); // string
console.log(error.data$.code); // models.BadRequestErrorCode
console.log(error.data$.message); // string
console.log(error.data$.issues); // ErrorIssue[]
console.log(error.data$.requestId); // string
}
}
}
}
run();Primary errors:
ModerationAPIError: The base class for HTTP error responses.AuthenticationError: The API key is missing, invalid or revoked. Status code401.RateLimitError: Too many requests. Retry after the number of seconds in theRetry-Afterheader. Status code429.BadRequestError: The request is malformed or a parameter is invalid. Status code400. *
Less common errors (10)
Network errors:
ConnectionError: HTTP client was unable to make a request to a server.RequestTimeoutError: HTTP request timed out due to an AbortSignal signal.RequestAbortedError: HTTP request was aborted by the client.InvalidRequestError: Any input used to create a request is invalid.UnexpectedClientError: Unrecognised or unexpected error.
Inherit from ModerationAPIError:
NotFoundError: The resource does not exist or the key cannot see it. Status code404. Applicable to 39 of 53 methods.*PermissionDeniedError: The API key cannot do this, or the plan limit for this resource is reached. Status code403. Applicable to 36 of 53 methods.*InternalServerError: Something went wrong on our side. Retry with backoff. Status code500. Applicable to 23 of 53 methods.*ConflictError: The request conflicts with the current state of a resource. Status code409. Applicable to 2 of 53 methods.*ResponseValidationError: Type mismatch between the data returned from the server and the structure expected by the SDK. Seeerror.rawValuefor the raw value anderror.pretty()for a nicely formatted multi-line string.
* Check the method documentation to see if the error is applicable.
The default server can be overridden globally by passing a URL to the serverURL: string optional parameter when initializing the SDK client instance. For example:
import { ModerationApi } from "@moderation-api/sdk";
const moderationApi = new ModerationApi({
serverURL: "https://api.moderationapi.com/v1",
secretKey: process.env["MODAPI_SECRET_KEY"] ?? "",
});
async function run() {
const result = await moderationApi.analytics.summary();
console.log(result);
}
run();The TypeScript SDK makes API calls using an HTTPClient that wraps the native
Fetch API. This
client is a thin wrapper around fetch and provides the ability to attach hooks
around the request lifecycle that can be used to modify the request or handle
errors and response.
The HTTPClient constructor takes an optional fetcher argument that can be
used to integrate a third-party HTTP client or when writing tests to mock out
the HTTP client and feed in fixtures.
The following example shows how to:
- route requests through a proxy server using undici's ProxyAgent
- use the
"beforeRequest"hook to add a custom header and a timeout to requests - use the
"requestError"hook to log errors
import { ModerationApi } from "@moderation-api/sdk";
import { ProxyAgent } from "undici";
import { HTTPClient } from "@moderation-api/sdk/lib/http";
const dispatcher = new ProxyAgent("http://proxy.example.com:8080");
const httpClient = new HTTPClient({
// 'fetcher' takes a function that has the same signature as native 'fetch'.
fetcher: (input, init) =>
// 'dispatcher' is specific to undici and not part of the standard Fetch API.
fetch(input, { ...init, dispatcher } as RequestInit),
});
httpClient.addHook("beforeRequest", (request) => {
const nextRequest = new Request(request, {
signal: request.signal || AbortSignal.timeout(5000)
});
nextRequest.headers.set("x-custom-header", "custom value");
return nextRequest;
});
httpClient.addHook("requestError", (error, request) => {
console.group("Request Error");
console.log("Reason:", `${error}`);
console.log("Endpoint:", `${request.method} ${request.url}`);
console.groupEnd();
});
const sdk = new ModerationApi({ httpClient: httpClient });You can setup your SDK to emit debug logs for SDK requests and responses.
You can pass a logger that matches console's interface as an SDK option.
Warning
Beware that debug logging will reveal secrets, like API tokens in headers, in log messages printed to a console or files. It's recommended to use this feature only during local development and not in production.
import { ModerationApi } from "@moderation-api/sdk";
const sdk = new ModerationApi({ debugLogger: console });You can also enable a default debug logger by setting an environment variable MODAPI_DEBUG to true.
The client is both the default and a named export:
import ModerationApi from "@moderation-api/sdk";
// or
import { ModerationApi } from "@moderation-api/sdk";Request and response types are in @moderation-api/sdk/models/operations, shared types in @moderation-api/sdk/models, error classes in @moderation-api/sdk/models/errors. Webhook event types (WebhookEvent, QueueItemRejectedEvent, ...) are exported from the package root, next to validateWebhook:
import type { SubmitContentRequestBody, SubmitContentResponse } from "@moderation-api/sdk/models/operations";
import { PermissionDeniedError } from "@moderation-api/sdk/models/errors";
import type { WebhookEvent } from "@moderation-api/sdk";Upgrading from 4.x? Read MIGRATION.md.
Set a timeout in milliseconds for all requests on the client, or for one request:
const moderationApi = new ModerationApi({ timeoutMs: 10_000 });
await moderationApi.content.submit(
{ content: { type: "text", text: "Hello" } },
{ timeoutMs: 5_000 },
);Node.js 18 or later, Bun 1 or later, Deno, Cloudflare Workers and other runtimes with the Fetch API. See RUNTIMES.md for the full list and the recommended TypeScript compiler options.
Found a bug? Open an issue in this repository. This package is generated from the Moderation API OpenAPI spec, so pull requests to the generated code can't be merged as they are, but we use them to fix the generator.
This SDK is in beta, and there may be breaking changes between versions without a major version update. Therefore, we recommend pinning usage to a specific package version. This way, you can install the same version each time without breaking changes unless you are intentionally looking for the latest version.
While we value open-source contributions to this SDK, this library is generated programmatically. Any manual changes added to internal files will be overwritten on the next generation. We look forward to hearing your feedback. Feel free to open a PR or an issue with a proof of concept and we'll do our best to include it in a future release.