Install the Botmotive guard in Next.js or Node
This page helps you add @botmotive/guard to a Next.js, Express or other Node app, so it applies the fixes you choose in Botmotive.
The guard enforces your rules: blocks, throttles, allow rules and path denials. It also sends a compact record of each request to Botmotive, so you don't need another log source. If you already send logs from Vercel, Railway, Cloudflare, Fastly or your own server, turn the guard's logs off (see Logs below) so requests aren't counted twice.
What you need first
- A Botmotive account and a site. See Getting started.
- Your site ID, such as
my-shop. It is shown in Settings next to Site ID. - A token for the guard, which starts with
bm_. It needs both Fetch blocking rules and Send traffic logs. - Node 18 or later.
A new site starts with no token. Its install page makes one for you: open your site, choose Next.js or Node (or click Connection steps in Settings), and click Make a token. The token is shown only once, and Botmotive keeps only a hash of it. You can also make one in Settings:
- Open your site in the dashboard and click Settings.
- Under Tokens, click New token. Name it after what will use it, such as
Next.js app, and click Make token. - Click Copy and store the token somewhere safe.
Other tokens keep working. If an old token may have leaked, click Revoke next to it.
Install
Install the package:
npm install @botmotive/guard@^0.2.0Set two environment variables where your app runs:
BOTMOTIVE_SITE=my-shop BOTMOTIVE_TOKEN=bm_...When either is missing,
guardFromEnv()returnsnulland the guard does nothing. This keeps local development quiet.Add the guard to your app. Pick the section that matches it.
Next.js 16 (proxy.ts)
Create or edit proxy.ts at the root of your project, next to app/:
import type { NextFetchEvent, NextRequest } from 'next/server';
import { guardFromEnv } from '@botmotive/guard';
const botmotive = guardFromEnv();
export async function proxy(request: NextRequest, event: NextFetchEvent) {
const blocked = await botmotive?.check(request, event); // a 403 or 429 response, or null
if (blocked) return blocked;
// ...your own proxy logic, if any
}
Passing event lets the guard send its logs after the response, with event.waitUntil, so serverless instances don't freeze with records still waiting.
Next.js 15 and earlier (middleware.ts)
Use the same code in middleware.ts, and name the function middleware. The guard is written for the Node.js runtime. Middleware runs on the Edge runtime unless you set runtime: 'nodejs', and that setting needs Next.js 15.5 or later. See the Next.js 15 middleware reference.
export async function middleware(request: NextRequest) {
const blocked = await botmotive?.check(request);
if (blocked) return blocked;
}
export const config = { runtime: 'nodejs' };
If you have a matcher, only matching paths are checked. Keep it broad so path rules such as /xmlrpc.php still apply.
Other fetch-API servers (Hono, Remix and similar)
Call check() with the standard Request before your handler runs. Return its response when it isn't null.
Express, Connect and node:http
import { guardFromEnv } from '@botmotive/guard';
import { botmotive, robotsTxt } from '@botmotive/guard/express';
const guard = guardFromEnv();
app.set('trust proxy', 1); // so req.ip is the visitor, not your load balancer
app.use(botmotive(guard));
app.get('/robots.txt', robotsTxt(guard, 'User-agent: *\nAllow: /'));
Add app.use(botmotive(guard)) before your routes. For plain node:http, call the middleware first and pass your handler as next:
const check = botmotive(guard);
http.createServer((req, res) => check(req, res, () => handler(req, res)));
Settings that matter
Client IP. Rules match on the visitor's IP address, so the guard must read the right one.
- The fetch guard (
check()) reads thex-real-ipheader by default. Railway's edge sets it. - The Express middleware uses
req.ip, so set Express'strust proxyto match your setup. - To read another header, set
BOTMOTIVE_IP_HEADERtox-real-ip,x-forwarded-for,cf-connecting-ip,fly-client-iportrue-client-ip. In Express you can also pass{ ipHeader: 'cf-connecting-ip' }as the second argument tobotmotive().
The header is trusted as-is, so pick one that only your edge can set. The one exception is cf-connecting-ip, which the Express middleware trusts only when the connection comes from a Cloudflare range or a private address. A fetch Request doesn't carry the connection's address, so pass the remoteIp option to get the same check. Without it, use cf-connecting-ip only when your origin accepts traffic from Cloudflare alone. With x-forwarded-for, the guard takes the rightmost public address.
Several processes or servers. Throttle counters live in memory, per process. With several replicas or serverless instances, each one enforces its own share of a limit.
Logs. The guard batches a record of each request (method, path, status, user agent, IP, timing and header names) and sends it gzipped every 10 seconds or 500 requests. It never sends cookies, the Authorization header or request bodies, and it replaces the values of query parameters that look secret, such as token or password, with redacted. If Botmotive can't be reached it keeps up to 10,000 records in memory, drops the oldest beyond that, and retries with backoff. Requests never wait for it.
- A proxy can't see your app's final status, so
check()records passed requests with status0(unknown). The Express middleware records the real status. - To record a request yourself, call
botmotive.log(request, status). - To turn logs off, set
BOTMOTIVE_LOGS=off, or passlogs: falsetocreateGuard(). Do this when your host already sends Botmotive your logs.
Other options. createGuard({ site, token, api, ipHeader, refreshSeconds, firstLoadMs, logs, onError }) builds a guard without environment variables. Defaults: api is https://api.botmotive.io (or BOTMOTIVE_API), refreshSeconds is 60, and firstLoadMs is 1500. The first request waits at most firstLoadMs for the rules.
robots.txt. Your AI bot choices and opt-outs are robots.txt rules. In Next.js, add them to app/robots.ts:
import type { MetadataRoute } from 'next';
import { guardFromEnv } from '@botmotive/guard';
const botmotive = guardFromEnv();
export const dynamic = 'force-dynamic';
export default async function robots(): Promise<MetadataRoute.Robots> {
return { rules: [{ userAgent: '*', allow: '/' }, ...((await botmotive?.robotsRules()) ?? [])] };
}
Keep the dynamic = 'force-dynamic' line. Without it, Next.js caches robots.ts, so later rule changes would not show.
If you serve robots.txt from a route instead, append await botmotive.robotsTxt('https://example.com') to its body. Passing your site's origin adds the License: line when the RSL license is on. In Express, the robotsTxt() handler shown above does this for you. Delete any static public/robots.txt, or it is served instead.
/license.xml. When Serve an RSL license at /license.xml is ticked in Settings, check() and the Express middleware answer /license.xml themselves.
Domain. In Settings, fill in Domain under Your site's address, then click Save. Botmotive then reads your robots.txt and sitemap once a day.
Check it worked
Run the check where your app runs, with the same environment variables:
npx -p @botmotive/guard@0.2.0 botmotive-checkIt prints
PASSorFAILfor the token, the API, your rules and a test log record, and exits with an error if any step fails. Within a minute, your site's page in the dashboard shows Guard connected: Node, last seen just now.Check traffic is arriving. Open your site in the dashboard and click the 15m tab.
Once requests arrive, the dashboard says Receiving data with a count of requests so far. Results follow 15 to 30 minutes after the first request, and the dashboard opens on the tab that has them.
Apply a block fix to a bot in the dashboard. Within a minute, request your site with that bot's user agent:
curl -i -A 'ExampleBot/1.0' https://example.com/You should see
403andForbidden.. A throttled visitor gets429with aRetry-Afterheader.
Updating and removing
- To update, run
npm install @botmotive/guard@latestand redeploy. - To use a new token, change
BOTMOTIVE_TOKENand restart or redeploy. - To pause the guard, unset
BOTMOTIVE_SITEorBOTMOTIVE_TOKEN.guardFromEnv()then returnsnull. - To remove it, delete the guard lines from
proxy.ts,middleware.tsor your Express app, and your robots.txt code. Then runnpm uninstall @botmotive/guard.
If something goes wrong
The guard fails open. If Botmotive can't be reached, the last rules stay in force. With no rules, every request goes through. guardFromEnv() logs problems as [botmotive] ... warnings.
- Everyone or no one is blocked by an IP rule. The guard is reading the wrong IP header. See Client IP above.
botmotive rules: HTTP 401. The site ID or token is wrong, or the token was replaced.botmotive logs: ingest answered 401(or 403). The token can fetch rules but can't send logs, as older guard tokens can't. Make a new token on the install page, or setBOTMOTIVE_LOGS=offif your host sends your logs. The guard tries again after an hour.[botmotive] BOTMOTIVE_SITE and BOTMOTIVE_TOKEN are not set. Shown once at startup in production. The guard is off until you set them.
For more, see Troubleshooting.