# Forward crawler requests

> Record AI crawlers and other bots that never run JavaScript from your server, with setup guides for Next.js, Cloudflare Workers and Pages, Express, Hono, PHP and WordPress.

Most crawlers and AI agents (GPTBot, ClaudeBot, PerplexityBot, Googlebot, link previews) fetch your HTML and never run JavaScript, so the tracking script never sees them. Your server does. Forward those requests to Reveata and they appear on the **Bot traffic** page with the rest of your [bot traffic](https://reveata.com/docs/bot-traffic).

## Create a request token

Open your website's **Settings → General → Bot traffic** and select **Create token** under **Request authentication token**. You need the admin role. The token starts with `dt_bot_` and is shown once: copy it into a server environment variable (for example `REVEATA_BOT_TOKEN`). Never put it in front-end code.

**Rotate** gives you a new token and stops the old one right away. **Delete** turns forwarding off. Under the token, the settings show when the last forwarded request arrived and how many came in the last 24 hours, so you can check your setup.

## Pick your setup

| Your server                       | Use                                                                  |
| --------------------------------- | -------------------------------------------------------------------- |
| Next.js, on Vercel or self-hosted | [`@reveata/ai-crawl/next`](#next-js) in middleware                |
| Cloudflare Workers                | [`@reveata/ai-crawl/cloudflare`](#cloudflare-workers)             |
| Cloudflare Pages                  | [`@reveata/ai-crawl/cloudflare`](#cloudflare-pages) as middleware |
| Express                           | [`@reveata/ai-crawl/express`](#express)                           |
| Hono (Workers, Bun, Deno, Node)   | [`@reveata/ai-crawl/hono`](#hono)                                 |
| PHP (Laravel, Symfony, plain PHP) | [The PHP snippet](#php)                                              |
| WordPress                         | [The Reveata plugin](#wordpress)                                    |
| nginx or Apache access logs       | [`reveata bots forward`](#from-access-logs)                         |
| Anything else                     | [The endpoint](#the-endpoint) directly                               |

The `@reveata/ai-crawl` package (`npm install @reveata/ai-crawl`) recognises the crawlers Reveata knows by their User-Agent on your server, so browsers and unknown clients are never sent. It sends in the background with a 2-second timeout and never slows down or breaks your responses. By default it sends AI crawlers, AI assistants and search engines; pass `categories: 'all'` to add link previews, SEO tools and uptime monitors. Every stored request counts towards your [bot allowance](https://reveata.com/docs/billing-plans-and-usage).

## The endpoint

```text
POST https://reveata.com/api/collect/bots
Authorization: Bearer dt_bot_…
Content-Type: application/json
```

The body is one request, or an array of up to 100:

| Field        | Type    | Required | Notes                                                                                      |
| ------------ | ------- | -------- | ------------------------------------------------------------------------------------------ |
| `path`       | string  | yes      | The requested path, 1 to 2048 characters. Any query string or fragment is dropped.         |
| `userAgent`  | string  | yes      | The request's `User-Agent` header, up to 1024 characters.                                  |
| `hostname`   | string  | no       | The requested host. It must be your website's domain, a subdomain or an additional domain. |
| `statusCode` | integer | no       | The HTTP status your server answered with, 100 to 599.                                     |
| `ts`         | string  | no       | When the request happened, ISO 8601. Defaults to now; at most 7 days back.                 |
| `ip`         | string  | no       | The client's IPv4 or IPv6 address, for [crawler verification](https://reveata.com/docs/crawler-verification). |
| `referrer`   | string  | no       | The request's `Referer` header, up to 2048 characters. Only its host name is kept.         |

Other fields are rejected. The `ip` is optional: when you send it, Reveata checks it against the IP ranges the crawler's operator publishes, marks the request verified or spoofed, and discards the address without storing it. Without it, the request is stored as unverifiable. Only send an address your platform guarantees (for example `cf-connecting-ip` on Cloudflare), never a header the client can set.

Reveata answers `202` with how many requests it received and how many it stored:

```json
{ "status": "ok", "data": { "accepted": 2, "stored": 1 } }
```

Only requests whose User-Agent is a known crawler or agent are stored. Requests from browsers, from crawler companies you turned off under **Crawlers to count**, for other hosts or outside the time window are skipped without an error, so it is safe to forward more than you need to.

## Try it with curl

```bash
curl -X POST https://reveata.com/api/collect/bots \
  -H "Authorization: Bearer $REVEATA_BOT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "path": "/blog/launch",
    "hostname": "example.com",
    "userAgent": "Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; GPTBot/1.2; +https://openai.com/gptbot)",
    "statusCode": 200
  }'
```

The request shows up on the Bots page within a few seconds.

## Next.js

Forward crawler requests from `middleware.ts` (`proxy.ts` on Next.js 16):

```ts
import { NextResponse, type NextFetchEvent, type NextRequest } from 'next/server';
import { aiCrawl } from '@reveata/ai-crawl/next';

const track = aiCrawl({
  host: 'https://reveata.com',
  token: process.env.REVEATA_BOT_TOKEN, // tracking is off while it is unset
});

export function middleware(request: NextRequest, event: NextFetchEvent) {
  track(request, event);
  return NextResponse.next();
}

export const config = { matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'] };
```

On Vercel, add `REVEATA_BOT_TOKEN` under **Project → Settings → Environment Variables**. The request is sent with `event.waitUntil` alongside your response, and the client IP comes from `x-real-ip`, which Vercel sets. Middleware runs before the page, so the status code is not sent. If you already use `@reveata/next`, `forwardBots` from `@reveata/next/server` does the same job.

## Cloudflare Workers

Wrap your Worker. The response is returned untouched; the status code and Cloudflare's `cf-connecting-ip` are sent afterwards with `ctx.waitUntil`:

```ts
import { withAiCrawl } from '@reveata/ai-crawl/cloudflare';

export default withAiCrawl({
  async fetch(request, env, ctx) {
    return fetch(request); // your Worker
  },
});
```

Set the token as a secret and your Reveata address as a variable:

```bash
npx wrangler secret put REVEATA_BOT_TOKEN
```

```toml
# wrangler.toml
[vars]
REVEATA_HOST = "https://reveata.com"
```

A Hono app on Workers works the same way: `export default withAiCrawl(app)`.

## Cloudflare Pages

Add a middleware file to your Pages project:

```ts
// functions/_middleware.ts
import { aiCrawlPages } from '@reveata/ai-crawl/cloudflare';

export const onRequest = aiCrawlPages();
```

Add `REVEATA_BOT_TOKEN` (encrypted) and `REVEATA_HOST` (`https://reveata.com`) under the project's **Settings → Variables and Secrets**. Pages runs Functions only for the routes `_routes.json` sends to them, so make sure it includes the pages you want to record.

## Express

```ts
import express from 'express';
import { aiCrawl } from '@reveata/ai-crawl/express';

const app = express();
app.set('trust proxy', 1); // behind a load balancer, so req.ip is the client
const crawl = aiCrawl({ host: 'https://reveata.com', token: process.env.REVEATA_BOT_TOKEN });
app.use(crawl);

// On shutdown, send what is still queued.
process.on('SIGTERM', () => void crawl.flush());
```

Requests are recorded when the response finishes, with its status code, and sent in batches every 2 seconds or 100 requests. `req.ip` is sent for verification: set Express's `trust proxy` so it is the client and not your load balancer.

## Hono

```ts
import { Hono } from 'hono';
import { aiCrawl } from '@reveata/ai-crawl/hono';

const app = new Hono();
app.use(aiCrawl({ host: 'https://reveata.com', token: process.env.REVEATA_BOT_TOKEN }));
```

On Node, Bun and Deno requests are batched like Express. To verify crawlers by IP there, pass `clientIp: (c) => getConnInfo(c).remote.address`, with `getConnInfo` from your runtime's Hono adapter. On Cloudflare Workers, wrap the app with `withAiCrawl` as shown above, since secrets live on `env` there.

## PHP

Put this at the top of your front controller (`public/index.php` in Laravel and Symfony), or include it from any PHP page. It only acts on known crawlers, and with PHP-FPM it sends after the response has gone to the client:

```php
<?php
// Reveata: record AI crawlers and search engines server-side.
function reveata_ai_crawl(): void
{
    $token = getenv('REVEATA_BOT_TOKEN');
    $ua = $_SERVER['HTTP_USER_AGENT'] ?? '';
    if (!$token || $ua === '') return;
    if (!preg_match('/GPTBot|ChatGPT-User|OAI-SearchBot|ClaudeBot|Claude-User|Claude-SearchBot|anthropic-ai|PerplexityBot|Perplexity-User|Googlebot|bingbot|Applebot|Amazonbot|Bytespider|CCBot|meta-externalagent|DuckAssistBot|MistralAI-User|cohere-ai|YouBot|DuckDuckBot/i', $ua)) return;

    $started = time();
    register_shutdown_function(function () use ($token, $ua, $started) {
        if (function_exists('fastcgi_finish_request')) fastcgi_finish_request();
        $hit = array_filter([
            'path' => parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/',
            'hostname' => $_SERVER['HTTP_HOST'] ?? null,
            'userAgent' => substr($ua, 0, 1024),
            'statusCode' => http_response_code() ?: null,
            'ts' => gmdate('Y-m-d\TH:i:s\Z', $started),
            'referrer' => $_SERVER['HTTP_REFERER'] ?? null,
            // REMOTE_ADDR is the client only when no proxy sits in front of PHP.
            'ip' => $_SERVER['REMOTE_ADDR'] ?? null,
        ], fn ($v) => $v !== null && $v !== '');
        $ch = curl_init('https://reveata.com/api/collect/bots');
        curl_setopt_array($ch, [
            CURLOPT_POST => true,
            CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . $token, 'Content-Type: application/json'],
            CURLOPT_POSTFIELDS => json_encode($hit),
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT_MS => 2000,
            CURLOPT_CONNECTTIMEOUT_MS => 1000,
        ]);
        curl_exec($ch); // fire and forget: a failure never reaches your page
        curl_close($ch);
    });
}
reveata_ai_crawl();
```

Set `REVEATA_BOT_TOKEN` in your server's environment (with Laravel's `.env`, read it with `env()` instead of `getenv()`). Behind Cloudflare, use `$_SERVER['HTTP_CF_CONNECTING_IP']` for `ip`; behind another proxy, leave `ip` out unless the proxy overwrites a header the client cannot set. The pattern lists the main AI crawlers, AI assistants and search engines; Reveata still decides which requests are crawlers, so a wider pattern only costs requests. It needs PHP 7.4 or newer with the curl extension.

## Any other server

The same few lines work in any server or edge function: when the request's User-Agent is a crawler, `POST` it to [the endpoint](#the-endpoint) in the background, with a short timeout. For JavaScript runtimes the adapters don't cover, `createAiCrawl` from `@reveata/ai-crawl` gives you `track()` (send now) and `queue()` with `flush()` (batched).

## Only count requests sent with the token

Crawlers that run JavaScript (headless browsers, some AI agents) are also reported by the tracking script. The script's endpoint is public, so anyone can post a visit with a crawler's User-Agent. Once your server forwards crawler requests, turn on **Only count crawler requests sent with this token** under the token in **Settings → General → Bot traffic**. From then on only the requests your server signs are stored, for the Bots page, AI crawler insights and your bot allowance. Deleting the token turns it off again, so crawler visits are never silently lost.

## WordPress

The [WordPress plugin](https://reveata.com/docs/wordpress) (version 0.3.0 or newer) forwards crawler requests for you: paste the token under **Settings → Reveata → Crawler requests**.

## From access logs

The `reveata` command-line tool reads an nginx or Apache access log (combined format) and sends the crawler requests of the last 7 days in batches of 100:

```bash
reveata bots forward /var/log/nginx/access.log --bot-token "$REVEATA_BOT_TOKEN" --hostname example.com
```

It reads standard input when no file is given, so `zcat access.log.2.gz | reveata bots forward` works too. See [API and CLI](https://reveata.com/docs/api-and-cli) to install it.

## Limits and errors

- Up to 600 requests a minute per website, each with up to 100 hits. Over the limit you get `429 rate_limited` with a `Retry-After` header; batch your requests if you forward a lot.
- `401 unauthorized`: no `Authorization: Bearer` header. `401 invalid_token`: the token was rotated or deleted. An address that sends 30 wrong tokens within a minute gets `429 rate_limited` until the minute is over.
- `400 validation_failed`: a field is missing, too long or not in the table above. `413 payload_too_large`: the body is over 256 KB.
- Requests for an archived website are accepted and not stored.
