Input Security and Content Moderation

Understand moderation classifications and use Express with the OpenAI Moderation API to block unacceptable input before calling a generative model.

🎯 Introduction

AI applications need to reject invalid requests and content that violates application policies before calling a generative model, preventing unnecessary calls and harmful content from entering generation. This article explains input validation, content moderation, and OpenAI Moderation API classifications, then uses Express to block requests when moderation rejects input or fails.


🧱 Input validation and content moderation

CheckWhat it examinesExample
Request validationWhether data meets the endpoint's contractQuestions must be nonempty and within the length limit
Content moderationWhether text may contain specified categories of harmful contentDetecting violent threats against others

Request validation cannot assess meaning. A separate moderation model classifies content rather than generating answers, allowing the application to decide whether to proceed before generation, without relying on the generative model to refuse.


🧰 The content moderation API

OpenAI provides a free Moderation API. Its omni-moderation-latest model supports text and images. Generative model calls may still incur charges.

Moderation categories

Main categoryMeaning
harassmentHarassing or abusive content directed at others
hateHateful content targeting protected groups
violenceContent involving violence, death, or physical injury
sexualContent intended to arouse sexual excitement, among other content
self-harmContent involving self-harm
illicitInstructions or advice for carrying out illicit acts

These categories include more specific subcategories. For example, harassment/threatening covers harassment involving threats of serious harm or violence.

Call the moderation model

Use Node.js 22, Express 5.1.0, and OpenAI SDK 5.12.2. Install dependencies in a separate directory:

npm install express@5.1.0 openai@5.12.2

Set your API key in the terminal (Bash/Zsh syntax):

export OPENAI_API_KEY='your API key'

Create moderation.mjs and call the moderation API directly first:

import OpenAI from 'openai';

const openai = new OpenAI();

const response = await openai.moderations.create({
    model: 'omni-moderation-latest',
    input: 'I will hurt you and make you pay.',
});

const result = response.results[0];

console.log(result.flagged);
console.log(JSON.stringify(result.categories, null, 4));
console.log(JSON.stringify(result.category_scores, null, 4));
node moderation.mjs

Possible output (categories and scores are constructed teaching examples, not measured results):

true
{
    "harassment": true,
    "harassment/threatening": true,
    "hate": false,
    "hate/threatening": false,
    "illicit": false,
    "illicit/violent": false,
    "self-harm": false,
    "self-harm/intent": false,
    "self-harm/instructions": false,
    "sexual": false,
    "sexual/minors": false,
    "violence": true,
    "violence/graphic": false
}
{
    "harassment": 0.98,
    "harassment/threatening": 0.95,
    "hate": 0.0001,
    "hate/threatening": 0.0001,
    "illicit": 0.0001,
    "illicit/violent": 0.0001,
    "self-harm": 0.0001,
    "self-harm/intent": 0.0001,
    "self-harm/instructions": 0.0001,
    "sexual": 0.0001,
    "sexual/minors": 0.0001,
    "violence": 0.8,
    "violence/graphic": 0.0001
}
FieldPurpose
flaggedWhether the moderation model flagged the input overall
categoriesWhich categories were flagged
category_scoresConfidence scores for each category (0–1)

For example, result.categories['harassment/threatening'] indicates whether the text was flagged as threatening harassment, while result.category_scores['harassment/threatening'] gives its score.

Change input to How can I learn JavaScript? and run again. You will usually see flagged set to false.

A moderation result is not a business decision. For example, an application for people seeking help may respond to a self-harm flag with appropriate support under its policy rather than denying service. This article's technical Q&A endpoint uses a simplified policy: reject generation when flagged is true.

Scores are not probabilities of actual risk. Validate custom thresholds against business test data and reassess them after model updates.

🛠 Implement AI input security checks

User input
Request validation
Request body, JSON syntax, field types, lengthInvalid → 400 / 413
Passed
Content moderation
Content flagged → 403
Moderation unavailable → 503
Passed
Call the generative model

Wrap moderation in a reusable function

Replace moderation.mjs with the following code for reuse by the endpoint:

import OpenAI from 'openai';

const openai = new OpenAI({
    timeout: 5000,
    maxRetries: 0,
});

export async function moderateQuestion(question) {
    const response = await openai.moderations.create({
        model: 'omni-moderation-latest',
        input: question,
    });

    const result = response.results?.[0];

    // Do not generate without a valid overall flag
    if (typeof result?.flagged !== 'boolean') {
        throw new Error('Invalid moderation result');
    }

    return result;
}

A five-second timeout and disabled automatic retries prevent moderation outages from blocking the endpoint for too long.

Validate the request

Create app.mjs. First limit the request body size and validate the question:

import express from 'express';
import OpenAI from 'openai';
import { moderateQuestion } from './moderation.mjs';

const app = express();
const openai = new OpenAI();

// Limit the size of the entire JSON request body
app.use(express.json({ limit: '4kb' }));

function validateQuestion(body) {
    if (typeof body?.question !== 'string') {
        return null;
    }

    const question = body.question.trim();

    // Limit trimmed string length, not token count
    if (question.length === 0 || question.length > 500) {
        return null;
    }

    return question;
}

Call the model after moderation passes

Add the endpoint to app.mjs:

app.post('/api/ask', async (request, response) => {
    const question = validateQuestion(request.body);

    if (question === null) {
        return response.status(400).json({ error: 'INVALID_INPUT' });
    }

    let result;

    try {
        result = await moderateQuestion(question);
    } catch {
        // Stop processing on moderation failure instead of skipping the check
        return response.status(503).json({ error: 'MODERATION_UNAVAILABLE' });
    }

    if (result.flagged) {
        return response.status(403).json({ error: 'CONTENT_REJECTED' });
    }

    try {
        // Verify that blocked requests never reach generation
        console.log('Calling generative model');
        const completion = await openai.chat.completions.create({
            model: 'gpt-4o-mini',
            messages: [{ role: 'user', content: question }],
        });

        return response.json({ answer: completion.choices[0].message.content });
    } catch {
        return response.status(502).json({ error: 'MODEL_UNAVAILABLE' });
    }
});

When moderation is unavailable, the application cannot determine whether input meets its policy, so it stops processing. This strategy is called failing closed.

Handle parsing errors and start the server

Finally, append this to app.mjs:

app.use((error, request, response, next) => {
    if (error.type === 'entity.too.large') {
        return response.status(413).json({ error: 'PAYLOAD_TOO_LARGE' });
    }

    if (error.type === 'entity.parse.failed') {
        return response.status(400).json({ error: 'INVALID_JSON' });
    }

    if (response.headersSent) {
        return next(error);
    }

    return response.status(500).json({ error: 'INTERNAL_ERROR' });
});

app.listen(3000, '127.0.0.1', () => {
    console.log('http://127.0.0.1:3000');
});

🛠 Test input security checks

Start the server:

node app.mjs

The terminal prints http://127.0.0.1:3000 after startup. Run the following tests in another terminal.

Test valid and invalid input

Create test.mjs to send the test requests:

const cases = [
    { name: 'Valid request', body: JSON.stringify({ question: 'What is Vue?' }) },
    { name: 'Wrong type', body: JSON.stringify({ question: 123 }) },
    { name: 'Whitespace only', body: JSON.stringify({ question: '   ' }) },
    { name: 'Text too long', body: JSON.stringify({ question: 'a'.repeat(501) }) },
    { name: 'Body too large', body: JSON.stringify({ question: 'a'.repeat(5000) }) },
    { name: 'Invalid JSON', body: '{' },
    { name: 'Threatening content', body: JSON.stringify({ question: 'I will hurt you and make you pay.' }) },
];

for (const item of cases) {
    const response = await fetch('http://127.0.0.1:3000/api/ask', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: item.body,
    });

    console.log(item.name, response.status, await response.json());
}
node test.mjs

Expected results:

TestStatus codeResponse body
Valid request200{"answer":"Vue is a JavaScript framework."}
Wrong type, whitespace only, text too long400{"error":"INVALID_INPUT"}
Body too large413{"error":"PAYLOAD_TOO_LARGE"}
Invalid JSON400{"error":"INVALID_JSON"}
Threatening content flagged403{"error":"CONTENT_REJECTED"}

If the threat is flagged, only the valid request adds a Calling generative model log entry. If it is not flagged, it reaches generation, illustrating the possibility of false negatives.

Simulate a moderation outage

Temporarily add the following at the start of moderateQuestion in moderation.mjs to simulate a failed moderation call. Restart the server and send a valid request from another terminal:

throw new Error('Test moderation outage');
curl -i http://127.0.0.1:3000/api/ask \
    -H 'Content-Type: application/json' \
    -d '{"question":"What is Vue?"}'

Expected response:

HTTP/1.1 503 Service Unavailable

{"error":"MODERATION_UNAVAILABLE"}

Confirm that no new generation log appears, then remove the test code and restart the server.


⚠️ Limitations of content moderation

ProblemResponse
Benign content is incorrectly flaggedProvide review or appeal options appropriate to the context
Harmful content is missedEvaluate moderation against a business test set
Input complies with content policy but violates business rulesEnforce business rules separately
Malicious instructions are not flaggedApply prompt injection defenses

Input moderation does not guarantee safe generation. Model output needs separate checks.


❓ Questions and answers

Q1: Why can the same text be flagged in several categories?

Moderation is multilabel classification, rather than a choice of exactly one category. For example, harassment with violent threats may trigger both harassment and violence.


🧪 Exercise

Extend the existing moderation rules with categorized rejection reasons: when flagged is true, use categories to find flagged categories and log their names on the server without logging the raw text.

Acceptance criteria: Flagged requests still return 403, their flagged categories appear in logs, and the generative model is not called.


🎉 You can now validate input and moderate content before an AI request reaches the generative model.