Vercel Logo

Add BotID

Advanced and optional

BotID is available on every plan, so this lesson works on Hobby. It's Advanced because it's code, and the rest of the course runs on the Firewall alone. Nothing later depends on it. To skip it, go to Read the Logs.

Last Tuesday, Claw & Order got a lunch order for 40 rolls from totally.real.7@example.com, pickup at noon. Then 24 more, all for 40 rolls, all at noon. Nobody came. The order bot from 1.3 can't get past Bot Protection anymore, so somebody upgraded it. It drives a real headless Chrome now, and a real browser passes a browser challenge.

Outcome

/api/order rejects bots with checkBotId(), real browsers still place orders, and verified AI assistants on an allowlist get through.

An invisible check

The usual answer to a form bot is a CAPTCHA. It works, and it also makes every hungry office manager pick out traffic lights before they can feed 30 people.

BotID is a check that runs in the browser without asking the person anything. When the page loads, a small script runs checks that a real browser passes and an automated one struggles to fake, even a headless Chrome. When the browser calls a route you've protected, BotID attaches headers with the result. On the server, checkBotId() asks Vercel to verify them.

Install it:

npm install botid

The browser half

Next.js runs instrumentation-client.ts in the browser before the app becomes interactive, which makes it the right place to start BotID early. Create it at the project root:

instrumentation-client.ts
import { initBotId } from "botid/client/core";
 
// BotID attaches its headers only to the requests listed here. The order form
// posts to /api/order, so that's the one we protect.
initBotId({
  protect: [{ path: "/api/order", method: "POST" }],
});

The protect list names the routes that should carry BotID's headers. Anything not on it goes out untouched, so preorders and page loads work exactly as before.

Older BotID instructions, including the README inside the botid package, also wrap next.config.ts with withBotId. The current setup guide says Vercel routes BotID's requests automatically, so leave next.config.ts alone.

The server half

Replace the two TODO comments in app/api/order/route.ts with a checkBotId() call, before the route reads the body:

app/api/order/route.ts
import { checkBotId } from "botid/server";
import { createOrder } from "@/lib/store";
 
export async function POST(request: Request) {
  // Locally, BotID calls everyone human. Set BOTID_DEV_BYPASS=BAD-BOT (or
  // GOOD-BOT) in .env.local to try the other branches without deploying.
  const verification = await checkBotId({
    developmentOptions: {
      bypass: process.env.BOTID_DEV_BYPASS as "HUMAN" | "BAD-BOT" | "GOOD-BOT" | undefined,
    },
  });
  if (verification.isBot) {
    return Response.json({ error: "We couldn't tell you from a bot. Try again from the order page." }, { status: 403 });
  }
 
  const body = await request.json().catch(() => null);

Checking first means a bot gets turned away before the route spends any work on its order. The error message is for the rare real person who gets caught: it tells them where to retry.

Try it on your laptop

In development, checkBotId() treats every request as human so it doesn't get in your way while you build. developmentOptions.bypass lets you pretend otherwise, and it's ignored in production. Create .env.local:

.env.local
BOTID_DEV_BYPASS=BAD-BOT

Start the dev server and send the order bot:

npm run dev
npm run scalper -- order --target http://localhost:3000 --count 3
Results
  403            3

The dev server terminal also prints Possible misconfiguration of Vercel BotId for each request. This is expected: the script never ran BotID's browser code, so its requests arrive without BotID's headers.

That's the branch working. An order from your browser on localhost gets a 403 too, because BAD-BOT applies to every request. Delete the line from .env.local and restart, and orders go through again.

Let the right assistants order

Marguerite's assistant, from 4.1, is a bot. checkBotId() reports it with isBot: true, so the route we just wrote turns it away. It also reports isVerifiedBot, verifiedBotName, and verifiedBotCategory for bots in Vercel's verified bots directory. Let's choose which ones we'll take orders from:

app/api/order/route.ts
import { checkBotId } from "botid/server";
import { createOrder } from "@/lib/store";
 
// Verified bots we'll take lunch orders from. Names come from Vercel's
// verified bots directory: https://vercel.com/docs/bot-management#verified-bots-directory
const WELCOME_BOTS = ["chatgpt-operator"];
 
export async function POST(request: Request) {
  // Locally, BotID calls everyone human. Set BOTID_DEV_BYPASS=BAD-BOT (or
  // GOOD-BOT) in .env.local to try the other branches without deploying.
  const verification = await checkBotId({
    developmentOptions: {
      bypass: process.env.BOTID_DEV_BYPASS as "HUMAN" | "BAD-BOT" | "GOOD-BOT" | undefined,
    },
  });
 
  const botName = "verifiedBotName" in verification ? verification.verifiedBotName : undefined;
  const welcomeBot = verification.isVerifiedBot && botName !== undefined && WELCOME_BOTS.includes(botName);
 
  if (verification.isBot && !welcomeBot) {
    return Response.json({ error: "We couldn't tell you from a bot. Try again from the order page." }, { status: 403 });
  }
 
  // ... validation stays the same
 
  const placedBy = welcomeBot && botName ? botName : "customer";
  const order = createOrder({ name, email, rolls, pickup, placedBy });
  return Response.json({ id: order.id, status: order.status, placedBy: order.placedBy }, { status: 201 });

chatgpt-operator is the example name the verified bots docs use. A list of names keeps the decision yours: a new verified bot doesn't get to order lunch until you add it. Recording placedBy lets the truck see which orders came from an assistant.

Locally, BOTID_DEV_BYPASS=GOOD-BOT reports isVerifiedBot: true, but also isBot: false and no verifiedBotName. This route treats that the same as HUMAN, so it tests nothing new here. Only a real verified bot on a deployment can exercise the allowlist.

Pro and Enterprise: Deep Analysis

BotID runs in Basic mode on every plan. Pro and Enterprise can switch the project to Deep Analysis for bots that imitate people well: vercel firewall rules update bot-id --action deep-analysis --yes, then vercel firewall publish --confirm-name claw-and-order. The route code stays the same.

Hands-on exercise 4.3

Put BotID on the order form, both halves.

Requirements:

  1. Install botid and create instrumentation-client.ts protecting POST /api/order.
  2. Call checkBotId() at the top of the POST handler and return 403 when isBot is true.
  3. Pass developmentOptions.bypass from BOTID_DEV_BYPASS and confirm BAD-BOT turns the bot away locally.
  4. Add the WELCOME_BOTS allowlist and record placedBy.
  5. Deploy with vercel deploy --prod and test the deployed route.
  6. Commit the code.

Implementation hints:

  • instrumentation-client.ts goes at the project root, next to package.json. The path in protect has to match the path the form posts to, /api/order, exactly.
  • Calling checkBotId() on a route the client doesn't protect makes every request look like a bot, because the headers never arrive. Your own browser gets 403 too.
  • Restart the dev server after changing .env.local.

Try It

First, put the code on the deployment. If .env.local still has BOTID_DEV_BYPASS, delete that line. Production ignores it, but it's one less thing to wonder about later.

vercel deploy --prod

Bot Protection challenges the order script before it ever reaches your route, so to watch BotID do its part on the deployment, put Bot Protection on log for a minute:

vercel firewall rules update bot-protection --action log --yes
vercel firewall publish --confirm-name claw-and-order
npm run scalper -- order --target "$URL" --count 5
Results
  403            5

Five 403s, from checkBotId() this time. Now place a lunch order from /order in your browser with the Network tab open. The order request carries extra headers from BotID's client script, and the response includes "placedBy": "customer".

Put Bot Protection back:

vercel firewall rules update bot-protection --action challenge --yes
vercel firewall publish --confirm-name claw-and-order

Commit

git add package.json package-lock.json instrumentation-client.ts app/api/order/route.ts
git commit -m "feat(order): verify lunch orders with BotID" -m "Verified AI assistants on WELCOME_BOTS can still order."

Leave .env.local out of git. The starter's .gitignore already does.

Done-When

  • instrumentation-client.ts protects POST /api/order
  • Locally, BOTID_DEV_BYPASS=BAD-BOT makes the order bot get 403
  • On the deployment, with Bot Protection on log, the order bot gets 403 from the route
  • A browser lunch order carries BotID's x-is-human header and returns "placedBy": "customer"
  • Bot Protection is back on challenge, and the code is committed

Troubleshooting

Your own browser order gets 403 on the deployment. Check that instrumentation-client.ts is deployed and lists { path: "/api/order", method: "POST" }. A route missing from protect makes every request look like a bot, and the function logs show Possible misconfiguration of Vercel BotId. Then hard-reload /order so the page picks up the current client code before you submit.

checkBotId() throws instead of returning a result. Read the error in the function logs. If it mentions x-vercel-oidc-token or VERCEL_OIDC_TOKEN, BotID couldn't get the project's OIDC token, which it needs to reach Vercel. Check the project's Security settings, where OIDC Federation lives, then redeploy.

Don't test the deployed route with curl. curl doesn't run BotID's script, so it gets 403 too, which is correct and also confusing.

Solution

The two files that put BotID on the order form:

instrumentation-client.ts
import { initBotId } from "botid/client/core";
 
// BotID attaches its headers only to the requests listed here. The order form
// posts to /api/order, so that's the one we protect.
initBotId({
  protect: [{ path: "/api/order", method: "POST" }],
});
app/api/order/route.ts
import { checkBotId } from "botid/server";
import { createOrder } from "@/lib/store";
 
// Verified bots we'll take lunch orders from. Names come from Vercel's
// verified bots directory: https://vercel.com/docs/bot-management#verified-bots-directory
const WELCOME_BOTS = ["chatgpt-operator"];
 
export async function POST(request: Request) {
  // Locally, BotID calls everyone human. Set BOTID_DEV_BYPASS=BAD-BOT (or
  // GOOD-BOT) in .env.local to try the other branches without deploying.
  const verification = await checkBotId({
    developmentOptions: {
      bypass: process.env.BOTID_DEV_BYPASS as "HUMAN" | "BAD-BOT" | "GOOD-BOT" | undefined,
    },
  });
 
  const botName = "verifiedBotName" in verification ? verification.verifiedBotName : undefined;
  const welcomeBot = verification.isVerifiedBot && botName !== undefined && WELCOME_BOTS.includes(botName);
 
  if (verification.isBot && !welcomeBot) {
    return Response.json({ error: "We couldn't tell you from a bot. Try again from the order page." }, { status: 403 });
  }
 
  const body = await request.json().catch(() => null);
  const name = typeof body?.name === "string" ? body.name.trim() : "";
  const email = typeof body?.email === "string" ? body.email.trim() : "";
  const rolls = Number(body?.rolls);
  const pickup = typeof body?.pickup === "string" ? body.pickup : "";
 
  if (!name || !email.includes("@") || !Number.isInteger(rolls) || rolls < 5 || rolls > 40 || !pickup) {
    return Response.json({ error: "Name, email, 5 to 40 rolls, and a pickup time, please." }, { status: 400 });
  }
 
  const placedBy = welcomeBot && botName ? botName : "customer";
  const order = createOrder({ name, email, rolls, pickup, placedBy });
  return Response.json({ id: order.id, status: order.status, placedBy: order.placedBy }, { status: 201 });
}

Then deploy them, with BOTID_DEV_BYPASS gone from .env.local:

vercel deploy --prod

The office manager gets lunch without picking out a single traffic light, and so does Marguerite's assistant.

Was this helpful?

supported.