# Next.js

URL: https://iscredible.com/docs/integrations/nextjs

> Check signups and expensive actions in a Next.js App Router app, from a server action or a route handler.

Call isCredible from the server side of your Next.js app: a server action or a route handler. Never call it from a client component, because your API key must stay on the server.

## Install

```bash
npm install is-credible
```

Add `ISCREDIBLE_API_KEY` to `.env.local` and to your host's environment variables.

## Create the client once

lib/iscredible.ts:

```typescript
import "server-only";
import { IsCredibleClient, IsCredibleError, decide, type Recommendation, type UserData } from "is-credible";

export const iscredible = new IsCredibleClient({
  apiKey: process.env.ISCREDIBLE_API_KEY!,
  timeoutMs: 3000, // keep signups fast
  maxRetries: 1
});

/** Returns APPROVE, REVIEW or DENY. Returns APPROVE when the check can't run (fail open). */
export async function screen(data: UserData, scenarioId?: string): Promise<Recommendation> {
  try {
    const result = await iscredible.verify(data, scenarioId ? { scenarioId } : {});
    return decide(result).action;
  } catch (err) {
    if (err instanceof IsCredibleError && err.status === 402) {
      console.error("isCredible: no active plan, checks are paused", err.code); // trial_ended or subscription_ended
    } else if (err instanceof IsCredibleError && err.status === 429) {
      console.warn("isCredible: rate limit or daily quota reached");
    } else {
      console.warn("isCredible unavailable, allowing the request", err);
    }
    return "APPROVE";
  }
}
```

The `server-only` package makes the build fail if a client component imports this file. Install it with `npm install server-only`, or leave the line out.

## Option 1: a server action

Check the signup before you create the user or send any email.

app/signup/actions.ts:

```typescript
"use server";
import { headers } from "next/headers";
import { screen } from "@/lib/iscredible";

export async function signUp(formData: FormData) {
  const h = await headers();
  const email = String(formData.get("email") ?? "");

  const action = await screen({
    email,
    ip: h.get("x-forwarded-for")?.split(",")[0]?.trim(),
    userAgent: h.get("user-agent") ?? undefined,
    deviceId: String(formData.get("deviceId") ?? "") || undefined,
    accountCreation: true
  });

  if (action === "DENY") return { error: "We couldn't create your account." };

  const user = await createUser(email, { needsVerification: action === "REVIEW" });
  return { ok: true, userId: user.id };
}
```

Add the device ID to the form as a hidden field. See [Send device signals](https://iscredible.com/docs/guides/device-signals) for a few lines that create one in the browser.

> **Note: The client's IP address**
>
> `x-forwarded-for` is set by your host or proxy (Vercel, Netlify, a load balancer). Its first entry is the client. If your app is not behind a proxy, read the address from your server or framework instead.

## Option 2: a route handler

Use a route handler when your signup form posts JSON, or when a mobile app calls your backend.

app/api/signup/route.ts:

```typescript
import { screen } from "@/lib/iscredible";

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

  const action = await screen({
    email,
    ip: req.headers.get("x-forwarded-for")?.split(",")[0]?.trim(),
    userAgent: req.headers.get("user-agent") ?? undefined,
    deviceId,
    accountCreation: true
  });

  if (action === "DENY") return Response.json({ error: "We couldn't create your account." }, { status: 403 });

  const user = await createUser(email, { needsVerification: action === "REVIEW" });
  return Response.json({ id: user.id });
}
```

The SDK has no dependencies and uses the built-in `fetch`, so it also runs in the Edge runtime.

## Protect expensive actions

For AI features and other metered work, check usage before you run the request. The SDK only calls the API when a check is due.

```typescript
import { iscredible } from "@/lib/iscredible";

const decision = await iscredible.checkUsage(
  user.id,
  { metric: "ai_tokens", used: tokensUsedThisMonth, limit: 100000 },
  { deviceId, ip }
);
if (decision.action === "DENY") return Response.json({ error: "Free limit reached" }, { status: 429 });
```

Wrap it in the same `try`/`catch` as `screen` so errors fail open. See [Stop resource abuse](https://iscredible.com/docs/guides/usage).

## Acting on the decision

| Decision | Suggested action |
|---|---|
| APPROVE | Create the account |
| REVIEW | Create it, but hold back free credits or API keys until the email or phone is verified |
| DENY | Show a neutral message. Don't reveal which check fired |

## Errors and limits

| Situation | What to do |
|---|---|
| Timeout, network error or 5xx | The SDK retries, then throws. Let the signup through and log it |
| `429` rate limit or daily quota | The SDK retries with backoff, then throws. Fail open, and upgrade if it happens every day |
| `402` with `code` `trial_ended` or `subscription_ended` | Your account has no active plan. Fail open and choose a plan in the dashboard |
| `401` or `403` | The key is wrong, revoked or missing. Fix it; fail open meanwhile |

See [Errors and limits](https://iscredible.com/docs/api/errors) for every status code.
