Log Search Engine and AI Crawlers in Next.js with proxy.ts and MongoDB
By Nitheesh Rajendran · · 8 min read
I wanted to know which crawlers actually visit this site: Googlebot, the AdSense crawler, AI bots, SEO tools. Analytics scripts can't tell me, because bots don't run JavaScript. Server logs on a serverless host are awkward to query. So I built a small crawler log into the app itself, using the Next.js proxy file and MongoDB. This post walks through the design and the decisions that kept it cheap and safe.
What the log needs to do
The requirements were short:
- Record one row per crawler request: which bot, which path, when.
- Never slow down or break a page request, even if the database is down.
- Never store IP addresses.
- Delete old data automatically.
Where to hook in: proxy.ts
Next.js 16 renamed middleware.ts to proxy.ts. It runs before a request is routed, so it sees every page request, including ones for pages that are statically generated. That makes it the right place to spot crawlers.
export function proxy(req: NextRequest, event: NextFetchEvent) {
const { pathname } = req.nextUrl;
if (pathname.startsWith("/admin")) { /* auth check, see another post */ }
if (pathname.startsWith("/api/")) return NextResponse.next();
const userAgent = req.headers.get("user-agent");
const bot = detectBot(userAgent);
if (bot && userAgent) {
const ip = (req.headers.get("x-forwarded-for") ?? "").split(",")[0].trim();
event.waitUntil(logCrawl({ userAgent, path: pathname + req.nextUrl.search, ip, bot }));
}
return NextResponse.next();
}
Two details matter here.
event.waitUntil. The proxy returns NextResponse.next() immediately, and the logging promise keeps running in the background. A visitor (or a bot) never waits for a database write. Without waitUntil, a serverless platform may freeze the function the moment the response is sent and your write never finishes.
Skipping /api/ and /admin. I only care about public page crawls. Admin traffic is mine, and API routes are not what search engines index.
The matcher also excludes static assets so the log doesn't fill with image and script requests:
export const config = {
matcher: ["/((?!_next/static|_next/image|favicon.ico).*)"],
};
Detecting the bot
Detection is a list of regular expressions tested against the user-agent, and the first match wins. Order matters because user-agents overlap. Googlebot-Image contains the string Googlebot, so the specific pattern must come before the generic one:
{ re: /Googlebot-Image/i, info: { name: "Googlebot Image", group: "Google", domains: [".googlebot.com", ".google.com"] } },
// ...
{ re: /Googlebot/i, info: { name: "Googlebot", group: "Google", domains: [".googlebot.com", ".google.com"] } },
Each entry has a display name, a group (Google, Search, AI, Social, SEO tools) for filtering in the dashboard, and a list of domains used for verification. Verification is covered in the next post, verifying Googlebot with reverse DNS.
A user-agent is just a header, so anyone can fake it. This list is for labeling traffic, not for trusting it.
Writing the row
await col.insertOne({
ts: new Date(),
bot: opts.bot.name,
group: opts.bot.group,
path: opts.path.slice(0, 300),
verified,
ua: opts.userAgent.slice(0, 200),
});
Notice what is not here: the IP address. The IP is used for verification and then thrown away. Only the verification result (true, false, or null when a bot can't be verified) is stored. I also cap the path and user-agent lengths so a hostile request can't write huge documents.
Indexes and automatic cleanup
The first time the function runs it creates two indexes:
await col.createIndex({ ts: 1 }, { expireAfterSeconds: 60 * 60 * 24 * 90 });
await col.createIndex({ bot: 1, ts: -1 });
The first is a TTL index: MongoDB deletes documents 90 days after their ts value, so the log cleans itself and stays small. The second makes the per-bot queries in the dashboard fast. A module-level indexReady flag stops the code from calling createIndex on every request.
Making it unable to break the site
The whole logging function is wrapped in a try/catch that swallows errors:
} catch {
// Logging must never affect a request.
}
If MongoDB is unreachable, a crawler still gets its page and I lose one log row. That trade is correct for a log. It would be wrong for anything where a lost write matters.
Limits you should know about
- Edge versus Node runtime. The proxy calls
node:dns(for verification), which works because the proxy runs on the Node.js runtime in Next.js 16. If your setup runs it on the edge runtime, DNS lookups will not be available. - Cold starts and the cache. The verification cache is an in-memory
Map, so each serverless instance has its own and it resets on cold start. That only costs a few extra DNS lookups. - Spoofed user-agents. Unverified rows can be fake. Treat the "AI" and "SEO tools" groups as labels.
- No bot rate limiting. This logs, it doesn't block.
What I do with it
I read the counts per crawler in an admin page, which also shows the daily totals and the most-crawled paths. When a page I expect to be indexed never appears in the Googlebot rows, that is the first signal that something is wrong. The next post shows what the numbers looked like after 90 days.