use case · next.js

Next.js spam detection that stays server-side.

Updated November 7, 2026

In Next.js, call SiftFy from a Route Handler or Server Action, never from a Client Component. Use fetch with AbortSignal.timeout(2000), keep SIFTFY_KEY server-only, and fail open on transport errors. Drop only above the response's max_confidence; queue the 0.50-to-ceiling band for review.

The App Router makes the server boundary explicit. That is good news for spam filtering: the key never reaches the browser, and the score can decide what happens before a lead hits your inbox.

route handler

The App Router pattern.

A Route Handler is the smallest server surface for a form POST. Read the body, classify the text, and branch into allow, review, and drop. Keep the response identical for every outcome so a spammer cannot learn which threshold they hit.

typescriptapp/api/contact/route.ts
// app/api/contact/route.ts
import { NextResponse } from "next/server";

type Result = { spam_probability: number; max_confidence?: number | null };

export async function POST(req: Request) {
  const { email, message } = await req.json();

  let result: Result = { spam_probability: 0, max_confidence: null };
  try {
    const response = await fetch("https://api.siftfy.io/v1/predict", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "X-API-Key": process.env.SIFTFY_KEY!,
      },
      body: JSON.stringify({ text: message }),
      signal: AbortSignal.timeout(2000),
    });
    if (response.ok) result = await response.json();
  } catch {
    // Fail open: a classifier outage must not break the form.
  }

  const score = result.spam_probability;
  const ceiling = result.max_confidence ?? null;

  if (ceiling !== null && score > ceiling) {
    // Silent success: never teach the spammer which field tripped.
    return NextResponse.json({ ok: true });
  }

  if (score >= 0.5) {
    await queueForReview({ email, message, score });
  } else {
    await sendLead({ email, message });
  }

  return NextResponse.json({ ok: true });
}

response shape

What to read from the response.

FieldTypeUse it for
spam_probabilitynumberCalibrated score from 0 to 1. Treat 0.50 as the review floor.
max_confidencenumberThe highest score the model may return alone. Compare against it before dropping.
likelihoodlow | medium | highDisplay bucket. Do not route on this field.
detected_languagestringLanguage used for calibration; non-English ceilings can be lower.
score_sourcemodel | typesafeWho produced the score. Only relevant if you have live escalation enabled.
Allow0.00–0.50
Review0.50–ceiling
Drop> ceiling
The ceiling is max_confidence from each response, not a constant. The bar shows 0.84 as an example; read the real value per request.

server action

If your form uses a Server Action.

Server Actions run on the server, so the same call works. The difference is that the function receives FormData instead of a Request. Keep the timeout and fail-open logic identical.

typescriptapp/actions/contact.ts
// app/actions/contact.ts
"use server";

export async function submitContact(formData: FormData) {
  const message = String(formData.get("message") ?? "");
  const email = String(formData.get("email") ?? "");

  const result = await fetch("https://api.siftfy.io/v1/predict", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "X-API-Key": process.env.SIFTFY_KEY!,
    },
    body: JSON.stringify({ text: message }),
    signal: AbortSignal.timeout(2000),
  })
    .then((r) => (r.ok ? r.json() : null))
    .catch(() => null);

  if (result?.max_confidence != null && result.spam_probability > result.max_confidence) {
    return { ok: true };
  }

  if ((result?.spam_probability ?? 0) >= 0.5) {
    await queueForReview({ email, message });
  } else {
    await sendLead({ email, message });
  }
  return { ok: true };
}

avoid these

Four Next.js mistakes that leak the key or the lead.

Calling from a Client Component

A browser call exposes the API key and lets a spammer probe the threshold. Keep the fetch in a Route Handler, Server Action, or other server-only module.

Using NEXT_PUBLIC_ for the key

Next.js inlines any NEXT_PUBLIC_ variable into the client bundle. The SiftFy key must be a server-only environment variable, not a public one.

No timeout on the fetch

A request without an AbortSignal can hold a serverless invocation open until the platform limit. Use AbortSignal.timeout(2000) and fail open.

Hard-coding 0.85

The model's ceiling is below 0.85, so a fixed 0.85 drop never fires on model-only evidence. Read max_confidence from the response.

tests

Test the handler, not the browser.

Call the exported POST function with a Request, mock fetch, and assert the four outcomes: allow, review, drop, and fail-open. The runnable Next.js example is a good starting point.

Next.js integration questions

How do I add spam detection to a Next.js App Router route?

Create a Route Handler at app/api/contact/route.ts, read the JSON body, POST the message text to https://api.siftfy.io/v1/predict with your server-side SIFTFY_KEY, and return the same { ok: true } response whether the submission was allowed or dropped. Set AbortSignal.timeout(2000) and fail open on transport errors.

Can I use SiftFy in a Next.js Server Action?

Yes. A Server Action marked "use server" runs on the server, so it can hold the API key and call SiftFy directly. The pattern is the same as a Route Handler; the only difference is how the form reaches the function. Do not call the API from a Client Component.

Does SiftFy work on the Next.js Edge runtime?

Yes. The API is a standard HTTPS POST, so it works from the Edge runtime and the Node.js runtime. Use AbortSignal.timeout for the request budget; if your runtime or fetch polyfill does not support it, pass an AbortController with a manual timer instead.

What threshold should I use in Next.js?

Use 0.50 as the review floor and max_confidence from the response as the drop ceiling. Allow below 0.50, queue from 0.50 to the ceiling, and drop only above the ceiling. Do not hard-code 0.85: the model cannot reach that band alone, so the branch never fires.

How do I test the Next.js integration?

Mock global fetch in Vitest or Jest, call the Route Handler or Server Action directly, and assert three cases: allow below 0.50, review in the middle band, and drop above the ceiling. Add a fourth case where fetch rejects and assert the handler still returns a success response (fail open).

Why does the same API response look different in Next.js?

Next.js caches and revalidates fetch requests by default in some contexts. The SiftFy call is a POST with a per-message body, so it should not be cached; still, avoid adding `next: { revalidate }` or a cache tag to a classification request. If you need explicit behavior, set `cache: "no-store"`.

start free

Score your first Next.js submission in five minutes.

10,000 requests a month free, no card. One endpoint, a calibrated probability, and no puzzle for your users.