Next.js API Route Protection

NEXT.JSTYPESCRIPTREACT

Next.js is the standard for modern web apps. This example shows how to secure your API routes (App Router) against toxic user-submitted content before it ever reaches your database.

01. DEPENDENCIES

Install the SDK in your Next.js project:

npm install @safecomms/sdk

02. ROUTE HANDLER

Implementation for `app/api/submit-post/route.ts`:

import { NextRequest, NextResponse } from 'next/server';
import { SafeComms } from '@safecomms/sdk';

const safecomms = new SafeComms({ apiKey: process.env.SAFECOMMS_API_KEY });

// > POST_HANDLER /api/submit-post
export async function POST(req: NextRequest) {
  try {
    const { content, title } = await req.json();

    if (!content) {
      return NextResponse.json({ error: 'Content required' }, { status: 400 });
    }

    // 1. > SCAN_MULTIPLE_FIELDS
    // You can effectively scan both title and body by concatenating or making parallel requests
    const safeContent = await safecomms.text.analyze({ content });
    const safeTitle = await safecomms.text.analyze({ content: title });

    if (safeContent.flagged || safeTitle.flagged) {
      console.log('> BLOCKED_TOXIC_CONTENT');
      return NextResponse.json({
        error: 'Content Policy Violation',
        reason: safeContent.flagged ? safeContent.primaryCategory : safeTitle.primaryCategory
      }, { status: 403 });
    }

    // 2. > DB_PERSISTENCE
    // await db.post.create({ data: { title, content } });

    return NextResponse.json({ success: true, id: '12345' });

  } catch (error) {
    console.error('> SYSTEM_ERROR:', error);
    return NextResponse.json({ error: 'Internal Error' }, { status: 500 });
  }
}

> EDGE_COMPATIBILITY

The SafeComms JS SDK is isomorphic and works in standard Node.js environments as well as Edge Runtimes (Vercel Edge, Cloudflare Workers). Just ensure you handle environment variables correctly.