Content Moderation
Overview and use cases
Moderation performs pre-review of content on the write path: the targets are database table text and bucket images. It complements rowSecurity — rowSecurity governs who can read and write data, while Moderation governs whether written content is allowed to be saved.
In 2.12.0, bucket image moderation is supported when platform and project switches, bucket configuration, and the moderation service are enabled. The upload path reads image bytes and submits them using the Base64 adapter. Check object and record cleanup after errors; do not assume zero residual data.
2.9.0 additions: createConfig supports mode: 'post' | 'hybrid' (asynchronous post-review; can be selected for create or update only when Phase Two is enabled; when disabled, new requests reject these modes and existing configurations execute synchronously) and requireManualReviewOnViolation (violations routed to manual review, enabled by default; when disabled, violating documents become private_hold instead of quarantined). Document reads return moderationStatus (checking / pending / published / quarantined / private_hold / action_error) and moderationJobId; the moderation-state check permits the creator, last modifier, and privileged identities; actual reads remain subject to applicable authentication and database permissions. Lists with attribute filters may overcount total.
Prerequisites
API Key scopes:
moderation.config.write(create/update/delete configuration),moderation.config.read(read configuration),moderation.log.read(read logs). Place automated configuration in the Node Server SDK / controlled back ends / Functions; API Keys must not go into browser code.The project-level moderation switch and the moderation service are ready (check these two first when a write returns a moderation error).
The Console SDK does not need and cannot
new Moderation()(configuration is done directly on Console pages); the Web SDK only handles normal writes/uploads/reads after login and does not configure moderation rules.
Usage workflow
Create the table text moderation configuration (first time only; repeated create against an existing configuration will fail):
moderation.createConfig({ resourceType: ResourceType.Collections, // 或 'collections' resourceId: '<tableId>', databaseId: '<databaseId>', // collections 必填 mode: 'pre', // 2.9.0 起可选 'post' | 'hybrid'(需平台开启审核二期;关闭时新建或更新不接受这两种模式) requireManualReviewOnViolation: true, // 2.9.0:违规转人工复核(默认 true;false 时违规文档 private_hold) contentTypes: ['text'], // 首次 createConfig 必填 enabled: true })Then continue normal TablesDB writes (
createRow/updateRowetc.): moderation runs automatically on the write path — there is no explicit method likemoderate(). Pass → write succeeds; block → write returns an error.Read configuration / adjust / delete:
getConfig/updateConfig(changeenabledor moderation parameters; when only switchingenabled,contentTypescan be omitted and the existing configuration is preserved) /deleteConfig.Troubleshooting:
listLogs({ queries: [Query.equal('result', 'block')], total: true })filter audit logs by resourceType / resourceId / databaseId / result / timestamp / userId / contentType;getLog({ logId })look up a single record.
Key parameters and returns
resourceType:collections(tables) orbuckets(buckets);mode:pre/post/hybrid(post / hybrid require Phase Two for create or update; when disabled, execution of existing configurations falls back topre;hybridroutes to the sync / async path based on the platform's text length threshold).requireManualReviewOnViolationdefaults totrue(violation → quarantined); whenfalse, violating documents go to private_hold (visibility remains subject to creator, last-modifier and privileged-identity rules and existing permissions).column filtering semantics: the audit scope is determined automatically by the table schema——reviews
string/varchar/text/mediumtext/longtext(including array columns of these types); types such as integer / float / boolean / datetime / relationship are not reviewed; Email / URL / IP / Enum are string underneath, so they are also reviewed.contentTypes: ['text']does not mean "only reviewing columns named text", nor is it a column name list—it means "all text columns in the written data that meet the criteria".Bucket image moderation uses
resourceType: 'buckets'+contentTypes: ['image']; actual availability depends on environment, project, bucket configuration, and the moderation service.
Errors and boundaries
Write blocked: a TablesDB write returns a moderation error → first use
listLogsto find the blocking reason, then check the project-level moderation switch and moderation service configuration.For an existing image moderation configuration, verify environment switches, configuration and service status before deciding whether to change it; do not disable moderation without assessing the impact.
Image moderation does not cover every file type and depends on configuration and environment; do not pass local paths or arbitrary external image URLs to
createConfig.
SDK Category Differences
Server SDK (server-sdk/nodejs.md):
Moderationfull Moderation services (configuration CRUD + logs).Client SDK (client-sdk/web.md): no Moderation service; the browser only perceives write success/failure.
Console SDK (console-sdk/nodejs.md): the JS Console SDK has no Moderation service (configuration is done in Console pages); the Java Console SDK has the
Moderationservice.
Example Guide
JavaScript (configure moderation and query logs in Node): examples/javascript.md
Java:examples/java.md
Examples by language
The following provides examples by language, item by item along the usage workflow; each card can switch languages (synced across the page).
Create a table text moderation configuration
Moderation configuration is a server-side management plane: the Web SDK has no Moderation service (the browser only perceives write success/failure), and the JS Console SDK has none either (configuration is done directly in Console pages).
- Node.js (Server)
- Java
- Python
- Go
- REST (curl)
import { Client, Moderation, ResourceType } from 'agentbase-node-sdk';
const client = new Client()
.setEndpoint(process.env.APPBASE_ENDPOINT!) // Must include /v1
.setProject(process.env.APPBASE_PROJECT_ID!)
.setKey(process.env.APPBASE_API_KEY!); // moderation.config.write
{
const prepareRequest = client.prepareRequest.bind(client);
client.prepareRequest = (...args) => {
const request = prepareRequest(...args);
request.options.redirect = 'error';
return request;
};
}
const moderation = new Moderation(client);
await moderation.createConfig({
resourceType: ResourceType.Collections, // or 'collections'
resourceId: 'tasks',
databaseId: 'app-db', // collections is required
mode: 'pre', // v1 only supports prerequisite review
contentTypes: ['text'], // Required on first createConfig
enabled: true
});
// First time only: repeated create on an existing configuration will fail; afterwards continue with normal TablesDB writesimport io.agentbase.services.Moderation;
Moderation moderation = new Moderation(client); // For client initialization, see server-sdk/java.md
moderation.createConfig(ResourceType.COLLECTIONS, "tasks", Mode.PRE,
List.of("text"), "app-db", true);
// First time only: repeated create will fail; afterwards continue with normal TablesDB writesfrom agentbase.services.moderation import Moderation
moderation = Moderation(client) # Method surface mirrors the Node SDK, with snake_case parameters
moderation.create_config(
resource_type='collections', resource_id='tasks',
database_id='app-db', mode='pre',
content_types=['text'], enabled=True) # First time only; afterwards continue with regular TablesDB writesmod := agentbase.NewModeration(cl) // facade constructor; cl is a Client already loaded with an API Key
mod.CreateConfig("collections", "tasks", "pre", []string{"text"},
mod.WithCreateConfigDatabaseId("app-db"),
mod.WithCreateConfigEnabled(true))
// First time only: repeated create will fail; afterwards continue with normal TablesDB writes(
set +x
set -o pipefail
: "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
builtin printf 'X-Appwrite-Key: %s\n' "${APPBASE_API_KEY:?Set APPBASE_API_KEY}" | curl --disable --header @- -sS -X POST "$APPBASE_ENDPOINT/moderation-configs" \
-H 'Content-Type: application/json' \
-H "X-Appwrite-Project: $APPBASE_PROJECT_ID" \
-d '{"resourceType":"collections","resourceId":"tasks","databaseId":"app-db","mode":"pre","contentTypes":["text"],"enabled":true}'
# Read/update/delete: GET | PATCH | DELETE /moderation-configs/{resourceType}/{resourceId} (contentTypes can be omitted when only toggling enabled)
# Bucket image moderation uses resourceType=buckets + contentTypes=image; verify environment switches and service first
)Write data and trigger moderation
There is no explicit moderate() method: once a configuration is active, ordinary TablesDB writes (createRow / updateRow) automatically execute moderation in the pipeline——passing writes succeed, blocked writes return a moderation error.
- Node.js (Server)
- Web (user session)
- Java
- Python
- Go
- REST (curl)
import { TablesDB, ID } from 'agentbase-node-sdk';
const tablesDB = new TablesDB(client); // client is the same as the "Create table text moderation config" card
await tablesDB.createRow('app-db', 'tasks', ID.unique(), { title: '待审核的文本' });
// Allow: write succeeds; block: write errors → use the "Troubleshooting audit logs" card to locate the causeimport { TablesDB, ID } from 'agentbase-web-sdk'; // Prerequisite: the user is logged in
const tablesDB = new TablesDB(client);
await tablesDB.createRow({
databaseId: 'app-db',
tableId: 'tasks',
rowId: ID.unique(),
data: { title: '待审核的文本' } // Constrained by table/row permissions; moderation is also executed in the write path
});import io.agentbase.services.TablesDB;
TablesDB tables = new TablesDB(client); // For client initialization, see server-sdk/java.md
tables.createRow("app-db", "tasks", ID.unique(),
Map.of("title", "待审核的文本"), null, null); // Allow: write succeeds; block: write errorsfrom agentbase.services.tables_db import TablesDB
tables_db = TablesDB(client) # Method surface mirrors the Node SDK, with snake_case parameters
tables_db.create_row(
database_id='app-db', table_id='tasks', row_id=ID.unique(),
data={'title': '待审核的文本'})tables := agentbase.NewTablesDB(cl) // facade constructor; cl is a Client already loaded with an API Key
tables.CreateRow("app-db", "tasks", "<rowId>",
map[string]interface{}{"title": "待审核的文本"}) // Allow: write succeeds; block: write errorscurl -sS -X POST "$APPBASE_ENDPOINT/tablesdb/app-db/tables/tasks/rows" \
-H 'Content-Type: application/json' \
-H "X-Appwrite-Project: $APPBASE_PROJECT_ID" \
-H "X-Appwrite-Key: $APPBASE_API_KEY" \
-d '{"rowId":"task-1","data":{"title":"待审核的文本"}}'
# Pass: 201 write succeeds; Block: moderation_rejected → go to the "Review audit logs" card to locate the causeView, adjust and delete configuration
Do not repeat createConfig for an existing configuration (duplicate creation fails): query with getConfig, adjust/enable/disable with updateConfig (contentTypes can be omitted only when switching enabled; the original configuration is preserved), delete with deleteConfig. The Web SDK has no Moderation service.
These actions are independent; disabling or deleting affects moderation, so confirm the target and impact first. For Node.js and Python, first define the resource variable in the query block in the same session.
- Node.js (Server)
- Java
- Python
- Go
- REST (curl)
Read the configuration.
const tableResource = {
resourceType: ResourceType.Collections, // or 'collections'
resourceId: 'tasks',
databaseId: 'app-db'
};
const current = await moderation.getConfig(tableResource);Disable moderation after confirming the impact.
await moderation.updateConfig({ ...tableResource, enabled: false }); // Disable but keep the configurationEnable moderation.
await moderation.updateConfig({ ...tableResource, enabled: true }); // ReopenDelete the configuration only when no longer needed.
await moderation.deleteConfig(tableResource);Read the configuration.
Object current = moderation.getConfig(ResourceType.COLLECTIONS, "tasks", "app-db");Disable moderation after confirming the impact.
moderation.updateConfig(ResourceType.COLLECTIONS, "tasks", "app-db",
null, null, false); // Disable but keep the configuration; contentTypes can be omitted when only toggling enabledEnable moderation.
moderation.updateConfig(ResourceType.COLLECTIONS, "tasks", "app-db",
null, null, true); // ReopenDelete the configuration only when no longer needed.
moderation.deleteConfig(ResourceType.COLLECTIONS, "tasks", "app-db");Read the configuration.
table_resource = dict(resource_type='collections', resource_id='tasks', database_id='app-db')
current = moderation.get_config(**table_resource)Disable moderation after confirming the impact.
moderation.update_config(**table_resource, enabled=False) # Disabled but configuration retained; content_types may be omitted when only toggling enabledEnable moderation.
moderation.update_config(**table_resource, enabled=True) # ReopenDelete the configuration only when no longer needed.
moderation.delete_config(**table_resource)Read the configuration.
mod.GetConfig("collections", "tasks", mod.WithGetConfigDatabaseId("app-db"))Disable moderation after confirming the impact.
mod.UpdateConfig("collections", "tasks",
mod.WithUpdateConfigDatabaseId("app-db"),
mod.WithUpdateConfigEnabled(false)) // Disable but keep the configuration; ContentTypes can be omitted when only toggling enabledEnable moderation.
mod.UpdateConfig("collections", "tasks",
mod.WithUpdateConfigDatabaseId("app-db"),
mod.WithUpdateConfigEnabled(true)) // ReopenDelete the configuration only when no longer needed.
mod.DeleteConfig("collections", "tasks", mod.WithDeleteConfigDatabaseId("app-db"))Read the configuration.
(
set +x
set -o pipefail
: "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
: "${APPBASE_ENDPOINT:?Set APPBASE_ENDPOINT to the target API endpoint including /v1}"
APPBASE_ENDPOINT="${APPBASE_ENDPOINT%/}"
# Query: databaseId goes in query
builtin printf 'X-Appwrite-Key: %s\n' "${APPBASE_API_KEY:?Set APPBASE_API_KEY}" | curl --disable --header @- -sS "$APPBASE_ENDPOINT/moderation-configs/collections/tasks?databaseId=app-db" \
-H "X-Appwrite-Project: $APPBASE_PROJECT_ID"
)Disable moderation after confirming the impact.
(
set +x
set -o pipefail
: "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
: "${APPBASE_ENDPOINT:?Set APPBASE_ENDPOINT to the target API endpoint including /v1}"
APPBASE_ENDPOINT="${APPBASE_ENDPOINT%/}"
# Adjust / enable-disable: when only toggling enabled, omit contentTypes and the original configuration is preserved (databaseId goes in the body)
builtin printf 'X-Appwrite-Key: %s\n' "${APPBASE_API_KEY:?Set APPBASE_API_KEY}" | curl --disable --header @- -sS -X PATCH "$APPBASE_ENDPOINT/moderation-configs/collections/tasks" \
-H 'Content-Type: application/json' \
-H "X-Appwrite-Project: $APPBASE_PROJECT_ID" \
-d '{"enabled":false,"databaseId":"app-db"}'
)Delete the configuration only when no longer needed.
(
set +x
set -o pipefail
: "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
: "${APPBASE_ENDPOINT:?Set APPBASE_ENDPOINT to the target API endpoint including /v1}"
APPBASE_ENDPOINT="${APPBASE_ENDPOINT%/}"
# Delete (databaseId goes in the body)
builtin printf 'X-Appwrite-Key: %s\n' "${APPBASE_API_KEY:?Set APPBASE_API_KEY}" | curl --disable --header @- -sS -X DELETE "$APPBASE_ENDPOINT/moderation-configs/collections/tasks" \
-H 'Content-Type: application/json' \
-H "X-Appwrite-Project: $APPBASE_PROJECT_ID" \
-d '{"databaseId":"app-db"}'
)Troubleshoot audit logs
When a write is blocked (a TablesDB write returns a moderation error), first check the logs to locate the cause, then check the project-level moderation switch and moderation service configuration. The Web SDK has no Moderation service (the browser only perceives write success/failure).
- Node.js (Server)
- Java
- Python
- Go
- REST (curl)
import { Query } from 'agentbase-node-sdk';
const blocked = await moderation.listLogs({
queries: [Query.equal('result', 'block')],
total: true
}); // Filterable by resourceType / resourceId / databaseId / result / timestamp / userId / contentType, etc.
const one = await moderation.getLog({ logId: '<logId>' });import io.agentbase.Query;
io.agentbase.models.ModerationLogList blocked = moderation.listLogs(
List.of(Query.equal("result", "block")), true); // Filterable by resourceType / resourceId / databaseId / result / timestamp / userId / contentType, etc.
io.agentbase.models.ModerationLog one = moderation.getLog("<logId>");from agentbase.query import Query
blocked = moderation.list_logs(queries=[Query.equal('result', 'block')], total=True)
# Filterable by resource_type / resource_id / database_id / result / timestamp / user_id / content_type, etc.
one = moderation.get_log(log_id='<logId>')import "agentbase-go-sdk/query"
blocked, _ := mod.ListLogs(
mod.WithListLogsQueries([]string{query.Equal("result", "block")}),
mod.WithListLogsTotal(true)) // Filterable by resourceType / resourceId / databaseId / result / timestamp / userId / contentType, etc.
_ = blocked
one, _ := mod.GetLog("<logId>")
_ = onecurl -sS "$APPBASE_ENDPOINT/moderation-logs?queries[]=equal(\"result\",\"block\")&total=true" \
-H "X-Appwrite-Project: $APPBASE_PROJECT_ID" -H "X-Appwrite-Key: $APPBASE_API_KEY"
# Single item: GET /moderation-logs/{logId}