Skip to content

Add fraud checks to sign-up in Next.js

This recipe adds OpenContext to a sign-up form in a Next.js App Router project. It takes three files and two environment variables, and works in the sandbox before anyone turns on live traffic. The same steps apply to any framework: load the tag, send its request_id with the form, call the decision API on your server, and act on recommendation.

You need two sandbox keys from the console’s API keys page (see Keys and scopes):

.env.local
NEXT_PUBLIC_SITE_KEY=oc_pk_test_... # publishable: safe in the page
DECISION_SECRET_KEY=oc_test_... # secret: server only, decide + outcomes scopes

Never expose the secret key to the browser. Only names starting with NEXT_PUBLIC_ reach the page.

In app/layout.tsx, load the tag once for every page:

import Script from "next/script";
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>
{children}
<Script src="https://c.opencontext.com/t.js" data-key={process.env.NEXT_PUBLIC_SITE_KEY} strategy="afterInteractive" />
</body>
</html>
);
}

The form submits with script, so ask the tag for a request_id and send it along. collect always resolves, even when collection fails, so sign-up never waits on it for more than the tag’s timeout.

"use client";
declare global {
interface Window { __dc?: { collect: (event: string) => Promise<{ request_id: string | null }> } }
}
export function SignupForm() {
async function onSubmit(e: React.FormEvent<HTMLFormElement>) {
e.preventDefault();
const form = Object.fromEntries(new FormData(e.currentTarget));
const { request_id } = (await window.__dc?.collect("signup")) ?? { request_id: null };
const res = await fetch("/api/signup", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ ...form, request_id }),
});
// Show the result: account created, a verification step, or a neutral refusal.
}
return (
<form onSubmit={onSubmit}>
<input name="email" type="email" autoComplete="email" required />
<input name="password" type="password" autoComplete="new-password" required />
<button>Create account</button>
</form>
);
}

In app/api/signup/route.ts, call the decision API before you create the account. Set a timeout and decide in advance what happens if it fires: for sign-up, most teams let it through and review later.

import { NextRequest, NextResponse } from "next/server";
export async function POST(req: NextRequest) {
const body = await req.json();
const accountId = crypto.randomUUID(); // your own stable ID for the new account
let decision: { decision_id?: string; recommendation: string } = { recommendation: "review" };
try {
const res = await fetch("https://api.opencontext.com/v1/decision", {
method: "POST",
headers: { Authorization: `Bearer ${process.env.DECISION_SECRET_KEY}`, "Content-Type": "application/json" },
body: JSON.stringify({
request_id: body.request_id,
event_type: "signup",
account_id: accountId,
email: body.email,
ip: req.headers.get("x-forwarded-for")?.split(",")[0]?.trim(),
user_agent: req.headers.get("user-agent"),
}),
signal: AbortSignal.timeout(1500),
});
if (res.ok) decision = await res.json();
} catch {
// Timeout or network error: fall through with "review".
}
switch (decision.recommendation) {
case "allow":
// createAccount(accountId, body, decision.decision_id)
return NextResponse.json({ status: "created" });
case "step_up":
// Ask for an email code or passkey before creating the account.
return NextResponse.json({ status: "verify" });
case "review":
// Create the account with limits and queue it for review.
return NextResponse.json({ status: "created" });
default:
// deny: refuse with a neutral message, and never say why.
return NextResponse.json({ status: "refused" }, { status: 403 });
}
}

Store decision_id with the new account. You report outcomes against it later.

  1. Run the app and submit the form once in a normal browser.
  2. Open Transactions in the console. The sign-up is there with its device, reasons, and recommendation.
  3. If the decision has a no_request_id warning, the tag did not run: check the site key, its allowed domains, and your Content Security Policy (see Browser tag).

When you learn whether the account was good or bad, send an outcome against the decision_id. See Outcomes. Every outcome makes later decisions sharper.