Guide

Content Moderation in Next.js: Check Posts in Server Actions and Route Handlers

·11 min read

A Next.js app that accepts posts, comments, reviews, or profile bios needs to check that content on the server, before it's written to the database. If you check after the write, the post is already in your feed queries and caches. If you check in the browser, anyone can skip it with a single fetch call.

The App Router gives you two server-side places where writes happen: Server Actions and Route Handlers. This guide adds a moderation check to both with the Vettly content moderation API, shows how to treat each of the four possible decisions in the UI, covers images, and shows how to test your policy without sending real content.

What a check returns

Each call to POST /v1/check evaluates the content against a policy and returns an action. There are four:

  • allow: publish it.
  • warn: publish it, but the policy matched something minor (mild profanity, fictional violence). A good place for a content warning or a softer UI.
  • flag: don't publish yet. Send it to a person for review.
  • block: reject it.

The response also includes a decisionId (store it with the row, because it's how you look the decision up later in the dashboard or during an appeal) and a categories array of { category, score, triggered } entries. Filtering on triggered tells you which rules fired.

Which content lands in which bucket is decided by the policy, not by your code. New accounts come with starter policies. This guide uses moderate, which blocks hate speech, scams, self-harm, and illegal content, flags harassment, sexual content, and spam, and warns on profanity and violence. You can change any of that later in YAML without redeploying. The policies guide covers the format, and Moderation Policies as Code explains why it's built this way.

Setup

Install the Next.js package. It depends on @vettly/sdk and re-exports its ModerationClient:

installShell
npm install @vettly/nextjs server-only

Create an API key in the dashboard and add it to .env.local. Don't add the NEXT_PUBLIC_ prefix: that would inline the key into client bundles.

.env.localShell
VETTLY_API_KEY=vettly_live_...
# Optional: switch policies without a code change
VETTLY_POLICY_ID=moderate

Put the client in one server-only module. The server-only import makes the build fail if a Client Component ever imports this file, so the key can't end up in a bundle by accident.

lib/vettly.tsTypeScript
import 'server-only'
import { ModerationClient } from '@vettly/nextjs'
export type ModerationAction = 'allow' | 'warn' | 'flag' | 'block'
export interface ModerationResult {
decisionId: string
action: ModerationAction
categories: Array<{ category: string; score: number; triggered: boolean }>
}
export const POLICY_ID = process.env.VETTLY_POLICY_ID ?? 'moderate'
const client = new ModerationClient({
apiKey: process.env.VETTLY_API_KEY!,
timeout: 5000,
maxRetries: 1,
})
export async function checkText(content: string): Promise<ModerationResult> {
return client.check({ content, policyId: POLICY_ID, contentType: 'text' })
}
export async function checkImageUrl(url: string): Promise<ModerationResult> {
return client.checkImage(url, { policyId: POLICY_ID })
}
export { client as vettly }

Two settings matter here. By default the client waits up to 30 seconds per request and retries rate limits, 5xx responses, and network errors up to three times with exponential backoff. That suits a background job, but it's too slow for a form submit. Five seconds and one retry keeps the worst case short, and the next section handles what happens when that runs out.

The wrappers declare a narrow return type, so the app sees action as a four-value union, not a string.

Decide what each action means for your data

Put the mapping from decision to stored state in one place, because the Server Action, the Route Handler, and the image flow all use it:

lib/moderation.tsTypeScript
import type { ModerationAction } from './vettly'
export type PostStatus = 'published' | 'published_with_warning' | 'pending_review'
export function statusFor(action: ModerationAction): PostStatus | null {
switch (action) {
case 'allow':
return 'published'
case 'warn':
return 'published_with_warning'
case 'flag':
return 'pending_review'
case 'block':
return null
}
}

null means "don't write it". Since ModerationAction is a union, TypeScript errors if you leave a case out. Your feed query then filters on status in ('published', 'published_with_warning'), and authors can still see their own pending_review posts so they don't think the submission failed.

Moderating in a Server Action

Here's a Server Action for a post form. The order matters: validate, check, then write. The insert only happens after the decision comes back.

app/posts/actions.tsTypeScript
'use server'
import { revalidatePath } from 'next/cache'
import { checkText } from '@/lib/vettly'
import { statusFor } from '@/lib/moderation'
import { db, getCurrentUserId } from '@/lib/db'
export type PostFormState =
| { ok: true; status: 'published' | 'published_with_warning' | 'pending_review' }
| { ok: false; error: string; categories?: string[] }
| null
export async function createPost(
_prev: PostFormState,
formData: FormData
): Promise<PostFormState> {
const userId = await getCurrentUserId()
const body = String(formData.get('body') ?? '').trim()
if (!body) return { ok: false, error: 'Write something first.' }
if (body.length > 5000) return { ok: false, error: 'Posts are limited to 5,000 characters.' }
let result
try {
result = await checkText(body)
} catch (err) {
// Moderation unavailable: keep the post, but hide it until it can be checked.
console.error('Vettly check failed', err)
await db.post.create({
data: { authorId: userId, body, status: 'pending_review', decisionId: null },
})
return { ok: true, status: 'pending_review' }
}
const status = statusFor(result.action)
if (status === null) {
return {
ok: false,
error: 'This post breaks the community guidelines and was not published.',
categories: result.categories.filter((c) => c.triggered).map((c) => c.category),
}
}
await db.post.create({
data: { authorId: userId, body, status, decisionId: result.decisionId },
})
revalidatePath('/posts')
return { ok: true, status }
}

db and getCurrentUserId stand in for your ORM and auth library. Some notes on the choices:

  • The length check runs before moderation. The API rejects content over 100 KB, and you don't want to pay for checks on input your own validation would reject anyway.
  • Errors fail closed to review, not to publish. If the API times out, the post is saved as pending_review. The user's work isn't lost, and nothing unchecked shows up in the feed. A scheduled job can re-check pending_review rows that have no decisionId. If you'd rather reject the submission and ask the user to try again, return an error instead.
  • Blocked posts aren't stored. Vettly keeps its own record of the decision, so you still have an audit trail without keeping the text in your tables. If you need to show users a history of rejected submissions, store them with a rejected status instead.

Showing the result in the form

useActionState gives the form the value the action returned, so each outcome can get its own message:

app/posts/post-form.tsxTSX
'use client'
import { useActionState } from 'react'
import { createPost, type PostFormState } from './actions'
const messages = {
published: 'Posted.',
published_with_warning: 'Posted. It will show behind a content warning.',
pending_review: 'Thanks. Your post is waiting for a quick review before it appears.',
} as const
export function PostForm() {
const [state, formAction, pending] = useActionState<PostFormState, FormData>(createPost, null)
return (
<form action={formAction}>
<textarea name="body" required maxLength={5000} />
<button type="submit" disabled={pending}>
{pending ? 'Checking…' : 'Post'}
</button>
{state?.ok && <p role="status">{messages[state.status]}</p>}
{state && !state.ok && (
<p role="alert">
{state.error}
{state.categories?.length ? ` (${state.categories.join(', ')})` : null}
</p>
)}
</form>
)
}

Think about how much to show on a block. Listing the triggered categories ("harassment") helps people who wrote something borderline fix it. On a platform that gets targeted abuse, it also helps people work out exactly where your thresholds are. Showing them is a product decision. Either way, don't echo scores back to the user.

For a flagged post, "waiting for review" is honest and doesn't accuse anyone, which matters because flagged content is the borderline bucket by design.

Moderating in a Route Handler

If a mobile app or a third-party client posts JSON, the check goes in a Route Handler. The logic is the same, but the response is an HTTP status:

app/api/comments/route.tsTypeScript
import { NextResponse } from 'next/server'
import { checkText } from '@/lib/vettly'
import { statusFor } from '@/lib/moderation'
import { db, getCurrentUserId } from '@/lib/db'
export async function POST(req: Request) {
const userId = await getCurrentUserId()
const { postId, body } = (await req.json()) as { postId: string; body: string }
if (typeof body !== 'string' || body.trim() === '') {
return NextResponse.json({ error: 'Comment body is required' }, { status: 400 })
}
const result = await checkText(body).catch(() => null)
const status = result ? statusFor(result.action) : 'pending_review'
if (status === null) {
return NextResponse.json(
{ error: 'blocked', decisionId: result!.decisionId },
{ status: 422 }
)
}
const comment = await db.comment.create({
data: { postId, authorId: userId, body, status, decisionId: result?.decisionId ?? null },
})
return NextResponse.json({ id: comment.id, status }, { status: 201 })
}

Return 201 for allow, warn, and flag, and include the status so the client knows whether the comment is visible yet. Use 422 for a block. Returning the decisionId with a block gives support something to look up if the user appeals.

The moderateRoute shortcut

@vettly/nextjs also exports moderateRoute, which wraps a handler and returns 403 when content is blocked. It's useful when block-or-pass is all you need, but read what it does before you use it:

  • It only acts on block. Flagged and warned content goes straight to your handler, and the handler isn't given the decision, so you can't store a decisionId or route flagged items to review.
  • If the moderation call throws, it logs the error and calls your handler anyway (it fails open).
  • With field: 'body', it reads the request body itself, so a handler that calls req.json() again throws "Body is unusable". Pass an extractor that reads a clone:
app/api/reviews/route.tsTypeScript
import { NextResponse, type NextRequest } from 'next/server'
import { moderateRoute } from '@vettly/nextjs'
import { db } from '@/lib/db'
export const POST = moderateRoute({
apiKey: process.env.VETTLY_API_KEY!,
policyId: 'moderate',
// Read a clone so the handler can still read the original body
field: async (req: NextRequest) => {
const { body } = await req.clone().json()
return String(body ?? '')
},
handler: async (req) => {
const { productId, body } = await req.json()
await db.review.create({ data: { productId, body } })
return NextResponse.json({ ok: true }, { status: 201 })
},
})

For anything that stores user content long term, the explicit version above is the better default.

Images

The same endpoint checks images with contentType: 'image', which the SDK wraps as checkImage(url, { policyId }). Pass a URL Vettly can fetch rather than base64. The check endpoint caps content at 100 KB, so a base64 data URI only works for very small images.

The flow that works with private storage:

  1. Upload the file to a private bucket (S3, R2, Supabase Storage, or anything else that can issue signed URLs).
  2. Generate a short-lived signed read URL on the server.
  3. Check it, then attach the image to the post or delete it.
app/posts/image-action.tsTypeScript
'use server'
import { checkImageUrl } from '@/lib/vettly'
import { statusFor } from '@/lib/moderation'
import { db, getCurrentUserId } from '@/lib/db'
import { getSignedReadUrl } from '@/lib/storage'
export async function attachImage(postId: string, objectKey: string) {
const userId = await getCurrentUserId()
// Short-lived URL Vettly can fetch; the object stays private.
const url = await getSignedReadUrl(objectKey, { expiresIn: 300 })
const result = await checkImageUrl(url)
const status = statusFor(result.action)
if (status === null) {
await db.upload.delete({ where: { key: objectKey } })
return { ok: false as const, error: 'That image can’t be posted here.' }
}
await db.postImage.create({
data: { postId, authorId: userId, objectKey, status, decisionId: result.decisionId },
})
return { ok: true as const, status }
}

Don't serve the object publicly until the check has passed. If the upload goes straight to a public CDN path, there's a window where anyone with the URL can see it. For post text plus several images in one decision, there's also POST /v1/check/multimodal, covered in the multi-modal guide. The image moderation guide goes into categories and thresholds for visual content.

Runtime notes

No runtime configuration is needed. Server Actions and Route Handlers default to the Node.js runtime, and the client calls the API with the global fetch. Keeping it in one module means requests share an instance.

Testing your policy with dry runs

You don't want your test suite sending "a deliberately nasty string" to a live model, and you can't make a model produce an exact score on demand anyway. The dry-run endpoint, POST /v1/check/dry-run, takes category scores you supply, runs your stored policy against them, and returns the action. No model is called.

In the SDK that's dryRun(policyId, mockScores). A table-driven test pins down the contract between your policy and your status mapping:

lib/moderation.test.tsTypeScript
import { describe, it, expect } from 'vitest'
import { vettly, POLICY_ID } from './vettly'
import { statusFor } from './moderation'
describe('moderate policy routing', () => {
it.each([
[{ harassment: 0.8 }, 'pending_review'],
[{ hate_speech: 0.9 }, null],
[{ violence: 0.75 }, 'published_with_warning'],
[{ harassment: 0.1, spam: 0.1 }, 'published'],
])('%o -> %s', async (scores, expected) => {
const { evaluation } = await vettly.dryRun(POLICY_ID, scores)
expect(statusFor(evaluation.action)).toBe(expected)
})
})

The lib/vettly.ts module imports server-only, so if your test runner isn't set up for it, mock that import (in Vitest, vi.mock('server-only', () => ({}))). If someone later edits the policy so harassment blocks instead of flags, this test fails and the behavior change goes through code review instead of reaching users.

To try a policy change before you save it, the REST endpoint also accepts the YAML inline in a policy field. The SDK's dryRun doesn't expose that field, so call the endpoint directly. The request schema requires content, but a dry run doesn't evaluate it:

dry-run.shShell
curl -X POST https://api.vettly.dev/v1/check/dry-run \
-H "Authorization: Bearer $VETTLY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"content": "dry-run",
"policyId": "moderate",
"policy": "name: test\nversion: \"1\"\nrules:\n - category: harassment\n threshold: 0.5\n provider: jev\n action: block\n",
"mockScores": { "harassment": 0.9 }
}'

For end-to-end tests, stub checkText at the module boundary, and keep one smoke test against the real API in CI to catch an expired key or a renamed policy.

A checklist before you ship

  • The API key is server-only (no NEXT_PUBLIC_, and import 'server-only' in the client module).
  • Every write path that stores user text or media calls the check first: Server Actions, Route Handlers, and any import or edit endpoints. Edits count too, because an approved post can be edited into something else.
  • Feed and search queries filter on status, and authors can see their own pending posts.
  • decisionId is stored with every moderated row.
  • The timeout and failure behavior are deliberate choices, not defaults.
  • Someone reviews the pending_review queue. Flagging without review just delays publication.

If you're on Supabase, the same ideas apply with row-level security doing the filtering. That version is in Supabase content moderation. For the full SDK surface, see the SDK reference and the Next.js integration docs. To see how your own content scores before writing any code, paste it into the playground.

Frequently asked questions

Should I moderate in Next.js middleware or in the Server Action?

In the Server Action or Route Handler that writes to the database. That code already has the parsed input and the user, it can store the decision ID next to the row, and it can handle allow, warn, flag, and block differently. Middleware only sees the raw request and can only pass it on or reject it.

Can I call Vettly from a Client Component?

Don't. The API key would ship in your JavaScript bundle, and a client-side check is easy to skip. Keep VETTLY_API_KEY without the NEXT_PUBLIC_ prefix and call the API from server code only.

What happens to a post if the Vettly API is down?

That's your choice. The pattern in this guide saves the post as pending_review so it stays hidden until it has been checked, which keeps the form working without publishing unchecked content.

How do I test moderation without sending real content?

Use the dry-run endpoint, POST /v1/check/dry-run, exposed in the SDK as dryRun(policyId, mockScores). It runs your stored policy against scores you supply and returns the action the policy would take, without calling a model.

Which policy ID should I start with?

New accounts get a set of starter policies, including moderate, strict, and permissive. moderate is a good default: it blocks hate speech, scams, self-harm, and illegal content, flags harassment, sexual content, and spam for review, and warns on profanity and violence.