Bot detection for Next.js 16 signup forms

Open in

Add bot detection to a Next.js 16 signup with a Route Handler or Server Action. See where proxy.ts fits and how to handle missing evidence or an API outage.

A code window with the post’s Next.js route handler, one line circled in pen.
From this post: the Next.js route handler.
On this page
  1. Where do Proxy, Route Handlers and Server Actions fit?
  2. Step 1: Add the script to the page with your form
  3. Step 2: Send the check from your server
  4. Server Actions work too
  5. Step 3: Submit your form once
  6. Switching to enforce
  7. Four things that bite people
  8. Where to put the strictest rule

For bot detection on a Next.js 16 signup form, collect the browser evidence on submit and evaluate it inside the Route Handler or Server Action that creates the account. The server can then stop an automated signup before it writes an account, and a genuine visitor sent for review can continue through email verification.

This App Router example starts in watch mode. It records the decision while your existing signup policy runs as usual. In enforce mode it acts on the decision at the point of account creation.

Where do Proxy, Route Handlers and Server Actions fit?

Next.js 16 renamed middleware.ts to proxy.ts. Proxy runs before the matched route and defaults to the Node.js runtime. A matcher controls which requests reach it. A page visit or prefetch can happen before anyone submits a form. Keeping the signup check in the mutation handler means those visits consume no checks. Next.js Proxy reference.

Use a Route Handler when the client submits JSON to a URL such as /api/signup. Use a Server Action when the form calls a server function with FormData. Both can evaluate the network token and browser event ID from that particular submission before changing account state. Next.js Route Handlers · Maskbreak evaluate reference.

Get a free API key

The Free plan includes 10,000 visitor checks a month with no card, and setup starts in watch mode, which logs every decision and blocks no one until you turn blocking on.

Step 1: Add the script to the page with your form

Put the async collector in the server-rendered signup page. The browser can download it while React hydrates the form.

tsx
// app/signup/page.tsx
import { SignupForm } from './signup-form';

export default function SignupPage() {
  return (
    <>
      <script async src="https://maskbreak.com/assets/sentinel.js" />
      <SignupForm />
    </>
  );
}

Collect evidence when the visitor submits the form. This also works when client-side navigation mounts a form after the collector has loaded. Sentinel.collect() resolves to { token, fingerprintEventId, tz } and waits up to five seconds for the browser check. If a content blocker prevents the script loading, the form still reaches your server and takes the verification path in enforce mode.

tsx
// app/signup/signup-form.tsx
'use client';
import { useEffect, useState } from 'react';

type Evidence = { token: string | null; fingerprintEventId: string | null; tz: string | null };
declare global {
  interface Window { Sentinel?: { collect(opts?: { timeout?: number }): Promise<Evidence> } }
}

export function SignupForm() {
  const [message, setMessage] = useState('');
  const [pending, setPending] = useState(false);
  const [ready, setReady] = useState(false);
  useEffect(() => { setReady(true); }, []);

  async function onSubmit(e: React.FormEvent<HTMLFormElement>) {
    const start = process.env.NEXT_PUBLIC_MASKBREAK_FORM_METRICS === '1' ? performance.now() : null;
    e.preventDefault();
    if (pending) return;
    setPending(true);
    setMessage('');
    const form = e.currentTarget;
    const evidence = window.Sentinel
      ? await window.Sentinel.collect().catch(() => null)
      : null;   // script missing or blocked: submit anyway

    try {
      const response = await fetch('/api/signup', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          email: (form.elements.namedItem('email') as HTMLInputElement).value,
          submitWaitMs: start === null ? undefined : Math.round(performance.now() - start),
          token: evidence?.token ?? null,
          fingerprintEventId: evidence?.fingerprintEventId ?? null,
          tz: evidence?.tz ?? null,
        }),
      });
      const result = await response.json();
      setMessage(response.ok ? result.message : result.error);
    } catch {
      setMessage('We could not reach signup. Please try again.');
    } finally {
      setPending(false);
    }
  }

  return (
    <form data-sentinel="" method="post" onSubmit={onSubmit}>
      <input name="email" type="email" required />
      <button type="submit" disabled={!ready || pending}>Create account</button>
      <p role="status">{message}</p>
    </form>
  );
}

If your app sets a Content-Security-Policy in its response headers, include the collector’s hosts in the existing directives:

csp
script-src  https://maskbreak.com https://mcl.maskbreak.com https://*.mcl.maskbreak.com https://mesu.maskbreak.com 'wasm-unsafe-eval'
connect-src https://mcl.maskbreak.com https://*.mcl.maskbreak.com wss://mcl.maskbreak.com wss://*.mcl.maskbreak.com https://mesu.maskbreak.com
worker-src  https://mesu.maskbreak.com blob:

Step 2: Send the check from your server

One server-only module makes the call. It sends whatever evidence arrived, including none: in watch mode a check without a token or a browser check id still has to reach Maskbreak, because that is how the console tells you which half is missing. It never throws, and it logs one line per check.

typescript
// lib/maskbreak.ts
import 'server-only';   // npm install server-only: the build fails if client code imports this file

export const MODE = process.env.MASKBREAK_MODE ?? 'watch'; // 'watch' | 'enforce'

export type Verdict = {
  decision: 'allow' | 'review' | 'block';
  risk_score: number;
  reasons: string[];
  device_evidence?: 'ok' | 'not_sent' | 'unavailable';
  degraded?: boolean;
  test?: boolean;
  sandbox?: boolean;
  sample?: boolean;
};

// Only coarse families leave your server.
export function signupBrowser(ua: string) {
  if (/iPhone|iPad|iPod/.test(ua)) {
    if (/CriOS/.test(ua)) return 'ios_chrome';
    return /Version\/.*Safari\//.test(ua) ? 'ios_safari' : 'ios_other';
  }
  if (/Android/.test(ua)) return /Chrome\//.test(ua) && !/EdgA|SamsungBrowser|OPR|; wv/.test(ua) ? 'android_chrome' : 'android_other';
  if (/Firefox\//.test(ua)) return 'firefox';
  if (/Chrome\//.test(ua)) return /Edg|OPR/.test(ua) ? 'other' : 'chrome';
  return /Version\/.*Safari\//.test(ua) ? 'safari' : 'other';
}

type Input = {
  signupTiming?: { browser: string; waitMs: number };
  token?: string | null;
  fingerprintEventId?: string | null;
  tz?: string | null;
  email?: string;
  accountId?: string;
};

export function signupEmail(value: unknown): string | null {
  const email = typeof value === 'string' ? value.trim() : '';
  return email.length <= 254 && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email) ? email : null;
}

// Returns the verdict, or null when there is none. Never throws.
export async function checkVisitor(input: Input): Promise<Verdict | null> {
  let result: Verdict | null = null;
  try {
    const res = await fetch('https://maskbreak.com/v1/evaluate', {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${process.env.MASKBREAK_API_KEY}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        event: 'signup',
        signupTiming: input.signupTiming,
        token: input.token || '',
        fingerprintEventId: input.fingerprintEventId || undefined,
        tz: input.tz || undefined,
        email: input.email,
        accountId: input.accountId,
      }),
      signal: AbortSignal.timeout(3000),
      cache: 'no-store',
    });
    if (res.ok) {
      const data = await res.json();
      if (data && ['allow', 'review', 'block'].includes(data.decision)) result = data;
    } else {
      console.warn('[maskbreak] HTTP', res.status);
    }
  } catch (err) {
    console.warn('[maskbreak] unavailable:', (err as Error).name);
  }
  // One line per check. Never log the key, the token or form data.
  console.log('[maskbreak]', JSON.stringify({
    mode: MODE,
    decision: result?.decision ?? null,
    reasons: result?.reasons ?? null,
    device_evidence: result?.device_evidence ?? null,
    degraded: result ? !!result.degraded : null,
  }));
  return result;
}

export function signupDecision(v: Verdict | null): 'continue' | 'verify' | 'refuse' {
  if (MODE !== 'enforce') return 'continue';
  if (!v || v.test || v.sandbox || v.sample) return 'verify';
  if (v.decision === 'block') return 'refuse';
  if (v.decision === 'allow' && !v.degraded && v.device_evidence === 'ok') return 'continue';
  return 'verify';
}

To measure signup speed, set NEXT_PUBLIC_MASKBREAK_FORM_METRICS=1 before building and on the server. The form times the wait before sending the signup request. The server forwards that timing and a browser family in its existing evaluation. Maskbreak counts which fields reached the server, including submissions with missing evidence. The report groups requests by browser. Timing fields and coverage.

The Route Handler validates the submission before spending a check. The createAccount import represents your existing signup service. It must enforce your usual validation and uniqueness rules, and keep the account pending until email ownership is verified when requireAdditionalVerification is true. A pending account gets no authenticated session or trial credit.

typescript
// app/api/signup/route.ts
import { NextResponse } from 'next/server';
import { checkVisitor, signupDecision, signupEmail, signupBrowser } from '@/lib/maskbreak';
import { createAccount } from '@/lib/accounts';

export async function POST(req: Request) {
  const body = await req.json().catch(() => null);
  const email = signupEmail(body?.email);
  if (!email) {
    return NextResponse.json({ error: 'Enter a valid email address.' }, { status: 400 });
  }

  const verdict = await checkVisitor({
    signupTiming: process.env.NEXT_PUBLIC_MASKBREAK_FORM_METRICS === '1' && Number.isSafeInteger(body.submitWaitMs) && body.submitWaitMs >= 0
      ? { browser: signupBrowser(req.headers.get('user-agent') || ''), waitMs: body.submitWaitMs } : undefined,
    token: typeof body.token === 'string' ? body.token : null,
    fingerprintEventId: typeof body.fingerprintEventId === 'string' ? body.fingerprintEventId : null,
    tz: typeof body.tz === 'string' ? body.tz : null,
    email,
  });

  const policy = signupDecision(verdict);
  if (policy === 'refuse') {
    return NextResponse.json({ error: 'Signup unavailable' }, { status: 403 });
  }
  const verify = policy === 'verify';
  await createAccount({ email, requireAdditionalVerification: verify });
  const message = verify ? 'Check your email to verify your signup.' : 'Signup received.';
  return NextResponse.json({ message }, { status: verify ? 202 : 201 });
}

Set MASKBREAK_API_KEY to your live key in your host's environment variables (for Vercel, the Production environment), never with a NEXT_PUBLIC_ prefix, which would ship it to every browser. Then redeploy.

Server Actions work too

For a Server Action, collect the same evidence from the submitting browser and add it to the FormData. The action uses the same server-side policy as the HTTP route. Your app can expose either entry point.

tsx
// app/signup/action-form.tsx
'use client';
import { useState } from 'react';
import { signup } from './actions';

export function SignupActionForm() {
  const [message, setMessage] = useState('');
  async function submit(formData: FormData) {
    const evidence = window.Sentinel
      ? await window.Sentinel.collect().catch(() => null)
      : null;
    if (evidence?.token) formData.set('monocle', evidence.token);
    if (evidence?.fingerprintEventId) formData.set('sentinel_fp', evidence.fingerprintEventId);
    if (evidence?.tz) formData.set('sentinel_tz', evidence.tz);
    setMessage(await signup(formData));
  }
  return (
    <form action={submit}>
      <input name="email" type="email" required />
      <button type="submit">Create account</button>
      <p role="status">{message}</p>
    </form>
  );
}
typescript
// app/signup/actions.ts
'use server';
import { checkVisitor, signupDecision, signupEmail } from '@/lib/maskbreak';
import { createAccount } from '@/lib/accounts';

export async function signup(formData: FormData) {
  const email = signupEmail(formData.get('email'));
  if (!email) return 'Enter a valid email address.';
  const verdict = await checkVisitor({
    token: formData.get('monocle')?.toString(),
    fingerprintEventId: formData.get('sentinel_fp')?.toString(),
    tz: formData.get('sentinel_tz')?.toString(),
    email,
  });
  const policy = signupDecision(verdict);
  if (policy === 'refuse') return 'Signup unavailable';
  const verify = policy === 'verify';
  await createAccount({ email, requireAdditionalVerification: verify });
  return verify ? 'Check your email to verify your signup.' : 'Signup received.';
}

Step 3: Submit your form once

Open the deployed page in an ordinary browser, wait a moment, and submit the form. The first check then appears in the Maskbreak console (if half of it did not arrive, the console says which half), and your server logs one [maskbreak] line. degraded: true means no network token arrived (the script was blocked or collect() was not called); device_evidence: "not_sent" means no browser check id arrived; "ok" with degraded: false is a complete check.

Switching to enforce

After comparing watch-mode events with the signups your team reviews, set MASKBREAK_MODE=enforce and redeploy. Exercise these cases in staging before applying the change to customers:

Submitted form or API responseExpected Route Handler outcome in enforce mode
Invalid email or malformed JSON400. No evaluation or account write.
Complete live allow with device evidence201. Continue normal signup.
Live review, incomplete allow, fixture, or API failure202. Send the visitor through your verification flow.
Live block403. No account write.

Use a local stub to exercise the complete-live-allow branch. The public sandbox returns flagged fixture responses, including for test_clean. The example deliberately sends those responses to verification in enforce mode.

On 26 November 2026 these snippets passed a production build on Next.js 16.4.6 with React 19.3.1. In Chrome, submitting each form with the collector blocked reached the verification path in enforce mode. The account write went to a local test service. The public sandbox supplied the fixture response, and local stubs supplied the other API outcomes.

Four things that bite people

  • Gating on isSuspicious. It is a legacy flag: your dashboard rules, your IP and visitor pins and the disposable-email check never change it. Route on decision.
  • Forgetting fingerprintEventId. Without it the response has no device block at all, so automation and fake-browser detection silently never run and you conclude the product does not work.
  • Skipping the call when a field is missing. Send it anyway. A check with no token is answered (marked degraded), and it is the only way the console can show you that the browser half is broken.
  • Blocking on review. review exists so you can step up, with email verification or a second factor, rather than refuse. Refuse on block.

Where to put the strictest rule

Signup is the obvious place to start and rarely where the money is. Promotion and referral redemption is where losses concentrate, and it is the action with essentially no legitimate automated use case.

Once accounts exist, pass accountId (your own server-side user id) on later calls. That is what enables device-to-account linking, which is how you catch one environment behind many accounts: a pattern no single request will ever show on its own.

The same check in other JavaScript stacks: SvelteKit, Express and Supabase, where the signup runs on Supabase’s side, so the check goes somewhere else.

Questions people ask

Where should bot detection run in Next.js 16?
Next.js 16 renamed middleware.ts to proxy.ts. Proxy defaults to Node.js and can route matching requests. Evaluate the submitted browser evidence in the Route Handler or Server Action that owns signup, before creating the account.
Should I gate on decision or isSuspicious?
On decision. isSuspicious is a legacy flag set by VPN, proxy, Tor, fake-browser, automation, emulator and virtual-machine evidence. Your dashboard rules and IP or visitor pins never change it, and neither does the disposable-email check, because those are applied to decision. The three values are allow, review, and block.
What happens if the Maskbreak API is down?
In watch mode the example lets the normal signup flow continue. In enforcement mode, route an unavailable or incomplete check to your verification step before granting access. A complete live allow can proceed, and a live block stops the signup.
Do I need the fingerprintEventId if I already send the token?
You need it for any device-layer detection. The token carries network signals; the fingerprint event id is what enables the device block in the response, including antidetect browser detection, automation detection, emulator and virtual machine flags, and the tampering score. Omit it and the response has no device object, which is a common reason an integration appears to detect nothing; the response's device_evidence field says whether the browser check arrived.

Paste it in, then watch the verdicts

The public sk_test_sandbox key returns the documented allow, review and block shapes with no account, so the failure path is testable before you go live; SDKs for Node, Python and PHP, or plain HTTP. The Free plan includes 10,000 visitor checks a month with no card, and setup starts in watch mode, so nothing is blocked until you turn blocking on.

Get started freeRead the API docs