Moderate comments and posts
Check each comment on your server before anyone else can see it, give the author a useful message when it isn't posted, and keep your stored copy in step with later reviewer decisions. Text is classified in the request, so most comments are published or refused straight away.
1. Set up the server client
Create an API key in Portal › API keys and keep it on your server with your project ID, as in the quick start. Choose what gets blocked or age-restricted in Policies and actions; the steps below work with any policy.
npm install calmlens
import { CalmLensServerClient } from "calmlens/server";
const client = new CalmLensServerClient({
apiKey: (process.env.CALMLENS_API_KEY ?? ""),
projectId: (process.env.CALMLENS_PROJECT_ID ?? ""),
});
2. Create a draft and classify it before publishing
Create a pending draft/version record in your database before calling CalmLens, with a unique version ID and its externalId. Commit it first so an early webhook can find it. In the example, comment.id identifies this immutable version, not a reusable ID for every edit.
In the endpoint that receives a new comment, call client.text.classify() with the text and an externalId that identifies the comment. It waits for the decision, which usually takes several seconds; see Waiting for the decision. Attach the returned asset ID and initial status to that existing draft, then answer the browser. The example’s saveComment helper must atomically preserve any newer status already applied by a webhook, rather than overwriting it with this response:
async function createComment(comment: { id: string; body: string }) {
const result = await client.text.classify({ text: comment.body, externalId: `comment-${comment.id}` });
const { status, flaggedCategories } = result.classification.moderation;
// Attach to the pre-created pending version; preserve newer webhook decisions.
await saveComment({ ...comment, assetId: result.id, status });
if (status === "allowed" || status === "limited" || status === "age-restricted") {
return Response.json({ id: comment.id, status }, { status: 201 });
}
return Response.json(
{ code: "comment/refused", categories: flaggedCategories },
{ status: 422 },
);
}
| Status | Response |
|---|---|
| allowed | Publish the comment. |
| limited | Publish the comment, but collapse it or sort it lower, and send no notifications for it. |
| age-restricted | Publish it only to viewers your app allows to see age-restricted content. |
| blocked or purged | Don't publish it. Tell the author why. |
Saving refused comments as well means a reviewer can still allow one later. For a purged comment, CalmLens has deleted its copy of the text; delete yours too if your policy requires it.
For a reply in a thread, also send its author and the earlier posts, so a reply such as "same to you" is read against what it answers; see Threaded moderation.
Every check is an upload, so it counts towards usage. Classify a comment when it is created and again when its text is edited. An externalId is unique within a project, so give each version its own, such as comment-42-v2; a repeat is refused with 409 asset/duplicate-external-id. Text has lower limits until billing is set up; see Free uploads.
3. Explain a refusal to the author
classification.moderation.flaggedCategories lists every category your policy acted on in the automated decision, such as harassment or hate, including any that alone would only limit or age-restrict the comment. The example returns them with a stable code, and the form below turns them into a message and keeps the author's text so they can edit it:
import { type FormEvent, useState } from "react";
const CATEGORY_NAMES: Record<string, string> = {
harassment: "harassment",
hate: "hate speech",
sexual: "sexual content",
violence: "violence",
"self-harm": "self-harm",
"criminal-activity": "criminal activity",
profanity: "profanity",
"personal-information": "personal information",
};
function refusalMessage({ categories = [] }: { categories?: string[] }) {
const names = categories.map((category) => CATEGORY_NAMES[category]).filter(Boolean);
return names.length
? `Your comment wasn't posted because it may contain ${names.join(", ")}. Edit it and try again.`
: "Your comment wasn't posted because it may break our community guidelines.";
}
type CommentFormProps = {
postId: string;
onPosted: (comment: { id: string; status: string }) => void;
};
export function CommentForm({ postId, onPosted }: CommentFormProps) {
const [sending, setSending] = useState(false);
const [error, setError] = useState("");
async function handleSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
const form = event.currentTarget;
setSending(true);
setError("");
const response = await fetch(`/api/posts/${postId}/comments`, {
method: "POST",
body: new FormData(form),
});
const result = await response.json();
setSending(false);
if (response.ok) {
form.reset();
onPosted(result);
} else {
setError(
result.code === "comment/refused"
? refusalMessage(result)
: "Your comment wasn't posted. Please try again.",
);
}
}
return (
<form onSubmit={handleSubmit}>
<label>
Comment <textarea name="body" required />
</label>
{error && <p role="alert">{error}</p>}
<button type="submit" disabled={sending}>
{sending ? "Posting…" : "Post"}
</button>
</form>
);
}
Name the categories in plain words and avoid quoting scores or thresholds back to the author. The category definitions describe what each one covers, and Reading classification results describes the rest of the report.
4. Handle reviewer changes
A reviewer can allow, limit, age-restrict, block or purge a comment after your endpoint answered. Subscribe a webhook in Portal › Webhooks & connectors to asset.allowed, asset.limited, asset.age-restricted, asset.blocked and asset.purged, and update the comment that matches the event's asset.externalId:
import { CalmLensError, parseWebhookEvent } from "calmlens/server";
const STATUS_EVENTS = new Set(["asset.allowed", "asset.limited", "asset.age-restricted", "asset.blocked", "asset.purged"]);
export async function POST(request: Request): Promise<Response> {
let event;
try {
event = await parseWebhookEvent({
payload: await request.text(), headers: request.headers,
secret: (process.env.CALMLENS_WEBHOOK_SECRET ?? ""),
});
} catch (error) {
if (CalmLensError.isCalmLensError(error)) return new Response(null, { status: 401 });
throw error;
}
const asset = event.asset;
if (asset?.externalId && STATUS_EVENTS.has(event.type)) {
// Apply only to this upload/version; reject stale events in your database.
await updateModerationStatus(asset.externalId, asset.classification.moderation.status, event.createdAt);
} else if (asset?.externalId && event.type === "asset.failed") {
await markModerationFailed(asset.externalId);
}
return new Response(null, { status: 204 });
}
Apply events to the matching version, and publish only the version currently selected by your application. A later allowance for version 1 must not publish version 2’s different text. Follow Reliable application updates for ordering and early deliveries.
Re-render from the stored status, so an allowed comment appears and a blocked one disappears without further changes. Reviewer decisions name a user as the event's actor; Status changes after publishing explains when they arrive. If you tell authors about decisions, send the message from this handler.
5. Render comments by status
Show each comment according to its stored status, using the rules in Using the decision: the author sees their refused comments with an explanation, and everyone else sees allowed and limited comments, and the age-restricted ones your app lets them see.
Every project serves jurisdictions with regional rules, so apply the viewer-specific delivery action as well as the stored base status. This also applies when you render text or serve files from your own storage.
6. Test with test inputs
Post the test input text codes for your project as comments to check refusals, messages and reviewer changes without writing harmful text. For unit tests, the SDK mock clients return any status without a network request; see Unit tests without the network.