---
title: "Limits in Code"
description: "An Advanced lesson for Pro and Enterprise. Create a Firewall rule your code can call, then use checkRateLimit from @vercel/firewall in the preorder route to count by phone number, a key the WAF can't read from a request body."
canonical_url: "https://vercel.com/academy/vercel-firewall/limits-in-code"
md_url: "https://vercel.com/academy/vercel-firewall/limits-in-code.md"
docset_id: "vercel-academy"
doc_version: "1.0"
last_updated: "2026-11-17T18:26:11.900Z"
content_type: "lesson"
course: "vercel-firewall"
course_title: "Protect Your App on Vercel"
prerequisites:  []
---

<agent-instructions>
Vercel Academy — structured learning, not reference docs.
Lessons are sequenced.
Adapt commands to the human's actual environment (OS, package manager, shell, editor) — detect from project context or ask, don't assume.
The lesson shows one path; if the human's project diverges, adapt concepts to their setup.
Preserve the learning goal over literal steps.
Quizzes are pedagogical — engage, don't spoil.
Quiz answers are included for your reference.
</agent-instructions>

# Limits in Code

# Limits in code

\*\*Note: Advanced: Pro and Enterprise\*\*

This lesson needs a second rate limiting rule, which Hobby's [rate limiting limits](https://vercel.com/docs/vercel-firewall/vercel-waf/rate-limiting#limits) don't allow. On Hobby, read along and skip to [Turn On Bot Protection](/academy/vercel-firewall/turn-on-bot-protection). Nothing later in the course depends on this lesson.

A guy named Duane has started showing up at the window with a shoebox full of confirmation codes. He has three phones and a proxy service that hands every request a fresh IP address, so the limit from 3.1 sees a different customer every time. Duane resells the rolls on the sidewalk for $45. What Duane can't scale is phone numbers. He uses real ones so his preorders look legitimate, and he only has three.

## Outcome

The preorder route allows one roll per phone number per window, counted by a Firewall rule your code calls with `checkRateLimit`.

## What the WAF can't see

Every WAF condition we've used reads something about the request itself: its path, its user agent, its IP, its fingerprint. The phone number is inside the JSON body, and the WAF doesn't parse bodies. Your route handler does.

The [Rate Limiting SDK](https://vercel.com/docs/vercel-firewall/vercel-waf/rate-limiting-sdk) connects the two. You create a rule in the Firewall with a **rate limit ID**, and your code asks the Firewall whether a given key is over that rule's limit. The Firewall counts, using whatever key your code hands it.

Install the package:

```bash
npm install @vercel/firewall
```

## Create the rule

The rule matches on its rate limit ID instead of a path. From the CLI:

```bash
vercel firewall rules add "Preorder per phone" \
  --condition '{"type":"rate_limit_api_id","op":"eq","value":"preorder-phone"}' \
  --action rate_limit \
  --rate-limit-window 600 \
  --rate-limit-requests 1 \
  --yes
vercel firewall diff
vercel firewall publish --confirm-name claw-and-order
```

One request per key per 10 minutes. In the dashboard, the same condition is the **If** dropdown option for SDK rules (currently **@vercel/firewall**), with `preorder-phone` as the rate limit ID.

"One roll per phone per day" would be nicer, but windows top out well short of a day. One per phone per 10 minutes stops a reseller from cycling three numbers through a rush, and that's the part that matters at 11am.

## Call it from the route

Find the TODO in `app/api/preorder/route.ts`:

```ts title="app/api/preorder/route.ts"
  // TODO (3.2, Advanced, Pro and Enterprise): One roll per phone number. Call checkRateLimit from
  // @vercel/firewall with the normalized phone as the rateLimitKey.

  const preorder = takeRoll({ name, phone: normalizePhone(phone), style });
```

Replace it with a call to `checkRateLimit`, keyed by the phone number's digits:

```ts title="app/api/preorder/route.ts" {1,5-23,25}
import { checkRateLimit } from "@vercel/firewall";

// ... validation stays the same

  // One roll per phone number, counted by the "preorder-phone" rule in the
  // Firewall. The WAF can't read a JSON body, so the key comes from code.
  const digits = normalizePhone(phone);
  try {
    const { rateLimited } = await checkRateLimit("preorder-phone", {
      request,
      rateLimitKey: `phone:${digits}`,
      timeout: 1000,
    });
    if (rateLimited) {
      return Response.json(
        { error: "That phone number already has a roll. Try again after the rush.", reason: "phone" },
        { status: 429 },
      );
    }
  } catch (error) {
    // If the check is slow, keep selling. The IP rate limit still sits in front.
    if (!(error instanceof Error && error.name === "TimeoutError")) throw error;
  }

  const preorder = takeRoll({ name, phone: digits, style });
```

`normalizePhone` from `lib/phone.ts` strips everything but digits, so `(207) 555-0147` and `207.555.0147` land in the same bucket. The `phone:` prefix keeps these keys apart from any other key you might add to this rule later.

The `timeout` is a choice about failure. If the Firewall takes more than a second to answer, `checkRateLimit` throws a `TimeoutError`. We keep selling in that case, because a slow check shouldn't close the window, and the IP limit from 3.1 is still in front. A ticketing site might choose the opposite and return a `503`.

## Two kinds of 429

The form already handles the WAF's `429` from 3.1. This one carries a reason and a message meant for the customer, so let's show it:

```tsx title="components/preorder-form.tsx" {2-7}
    if (response.status === 429) {
      // Our route sends JSON with a reason. The WAF's own 429 doesn't.
      const data = await response.json().catch(() => null);
      if (data?.reason === "phone") {
        setStatus({ state: "error", message: data.error });
        return;
      }
      setStatus({
        state: "error",
        message: "The window's slammed right now. Give it a few minutes and try again.",
      });
      return;
    }
```

Deploy with `vercel deploy --prod`.

## Hands-on exercise 3.2

Count preorders by phone number.

**Requirements:**

1. Install `@vercel/firewall`.
2. Add a rate limiting rule with the condition `rate_limit_api_id` equals `preorder-phone`, one request per 600 seconds. Publish it.
3. Call `checkRateLimit("preorder-phone", ...)` in `app/api/preorder/route.ts` with the normalized phone as `rateLimitKey`.
4. Return a `429` with `reason: "phone"` when the phone is over its limit.
5. Show that message in the preorder form.
6. Deploy, then test with your browser and with the bot.

**Implementation hints:**

- Pass `request` to `checkRateLimit`. It reads the headers the Firewall needs from it.
- The rate limit ID in code and in the rule must match exactly.
- Test from the browser first. Once the bot runs, your browser shares its IP bucket for 10 minutes.
- Testing a preview deployment needs extra setup; see the [SDK docs](https://vercel.com/docs/vercel-firewall/vercel-waf/rate-limiting-sdk#test-in-a-preview-deployment). Production works as is.

## Try It

If you ran the bot in the last 10 minutes, your IP is still over the `Preorder rush` limit. Wait out the window first. Restocking resets the rolls, and the Firewall's count keeps running. Then preorder from your browser. The first preorder gets a confirmation code, and the form turns into the confirmation card. Reload the page and preorder again with the same phone number. The second one gets "That phone number already has a roll. Try again after the rush."

Now send Duane. The bot cycles three phone numbers across 200 requests:

```bash
npm run scalper -- preorder --target "$URL" --phones 3
```

```text
preorder bot grabbing rolls with 3 phone numbers → https://claw-and-order.vercel.app  (200 requests)
Only point this at a deployment you own.

Results
  201            3
  429 (phone)    5
  429            192
```

Both layers show up in one run. The WAF's IP limit stopped 192 requests before they reached the function. Your two browser preorders used up part of the IP's 10, so eight bot requests got through to the route, and the phone limit stopped five of those. Duane gets three rolls, one per phone, which is what he'd get standing in line.

## Commit

```bash
vercel firewall rules list --json > firewall/rules.json
git add package.json package-lock.json app/api/preorder/route.ts components/preorder-form.tsx firewall/rules.json
git commit -m "feat(preorder): limit preorders to one per phone number"
```

## Done-When

- [ ] `Preorder per phone` is published with the `preorder-phone` rate limit ID
- [ ] A second browser preorder with the same phone shows "That phone number already has a roll. Try again after the rush."
- [ ] The bot with `--phones 3` gets about 3 `201`s (counts are per region, so one or two extra can happen)
- [ ] The results show both plain `429`s and `429 (phone)`
- [ ] The code and `firewall/rules.json` are committed

## Troubleshooting

**Every preorder goes through, even with the same phone.** The rule's ID doesn't match the code, or the rule isn't published. `checkRateLimit` returns `rateLimited: false` with `error: "not-found"` when no rule has that ID. Log the `error` field while you debug.

**The browser test gets the WAF's message instead of the phone message.** Your IP is still over the `Preorder rush` limit from an earlier bot run. Wait out the 10-minute window, or test the phone limit before running the bot.

## Solution

The finished preorder route:

```ts title="app/api/preorder/route.ts"
import { checkRateLimit } from "@vercel/firewall";
import { isValidPhone, normalizePhone } from "@/lib/phone";
import { getRollsLeft, takeRoll } from "@/lib/store";
import { MENU, type RollStyle } from "@/lib/truck";

export async function POST(request: Request) {
  const body = await request.json().catch(() => null);
  const name = typeof body?.name === "string" ? body.name.trim() : "";
  const phone = typeof body?.phone === "string" ? body.phone : "";
  const style = body?.style as RollStyle;

  if (!name || !isValidPhone(phone) || !(style in MENU)) {
    return Response.json({ error: "Name, a phone number, and a roll style, please." }, { status: 400 });
  }

  const digits = normalizePhone(phone);
  try {
    const { rateLimited } = await checkRateLimit("preorder-phone", {
      request,
      rateLimitKey: `phone:${digits}`,
      timeout: 1000,
    });
    if (rateLimited) {
      return Response.json(
        { error: "That phone number already has a roll. Try again after the rush.", reason: "phone" },
        { status: 429 },
      );
    }
  } catch (error) {
    if (!(error instanceof Error && error.name === "TimeoutError")) throw error;
  }

  const preorder = takeRoll({ name, phone: digits, style });
  if (!preorder) {
    return Response.json({ error: "Sold out. See you tomorrow." }, { status: 409 });
  }

  return Response.json({ confirmation: preorder.confirmation, rollsLeft: getRollsLeft() }, { status: 201 });
}
```

Duane still has three phones and a shoebox. The shoebox stays mostly empty now.


---

[Full course index](/academy/llms.txt) · [Sitemap](/academy/sitemap.md)
