なぜNext.js Middlewareが最適か
Next.js MiddlewareはVercelのEdge Networkで実行されるため、リクエストが実際のページ処理に到達する前にAIボットを遮断できます。レスポンスも高速で、サーバー負荷を最小化できます。
基本実装:全AIボットをHTTP 402で遮断
// middleware.ts
import { NextRequest, NextResponse } from "next/server";
const AI_BOT_PATTERN = new RegExp([
"GPTBot", "OAI-SearchBot", "ChatGPT-User",
"ClaudeBot", "anthropic-ai",
"PerplexityBot",
"Google-Extended",
"Bytespider",
"CCBot",
"cohere-ai",
"YouBot",
"Diffbot",
"Amazonbot",
"MistralBot",
].join("|"), "i");
export function middleware(request: NextRequest) {
const ua = request.headers.get("user-agent") ?? "";
if (AI_BOT_PATTERN.test(ua)) {
return new NextResponse(
JSON.stringify({ error: "License required", url: "https://monitor.microforge.works" }),
{
status: 402,
headers: { "Content-Type": "application/json" },
}
);
}
return NextResponse.next();
}
export const config = {
matcher: ["/((?!api|_next/static|_next/image|favicon).*)"],
};
Tollgate実装:ライセンス済みボットを通過させる
// middleware.ts
import { NextRequest, NextResponse } from "next/server";
const AI_BOT_PATTERN = /GPTBot|ClaudeBot|PerplexityBot|anthropic-ai|OAI-SearchBot/i;
async function verifyLicense(siteId: string, apiKey: string): Promise {
const res = await fetch(
`https://monitor-api.microforge.works/license/verify?site_id=${siteId}&api_key=${apiKey}`,
{ next: { revalidate: 300 } } // 5分キャッシュ
);
const data = await res.json();
return data.valid === true;
}
export async function middleware(request: NextRequest) {
const ua = request.headers.get("user-agent") ?? "";
if (!AI_BOT_PATTERN.test(ua)) return NextResponse.next();
// ライセンスキー確認
const apiKey = request.headers.get("x-api-key") ??
request.nextUrl.searchParams.get("api_key") ?? "";
const siteId = process.env.SITE_ID ?? "";
if (apiKey && siteId && await verifyLicense(siteId, apiKey)) {
return NextResponse.next();
}
return new NextResponse("Payment Required", { status: 402 });
}
export const config = {
matcher: ["/((?!api|_next).*)"],
};
特定パスのみブロック
export const config = {
// /blog/ と /docs/ のみAIボットをブロック
matcher: ["/blog/:path*", "/docs/:path*"],
};
AI Access Monitorと組み合わせる
AI Access Monitorのagent.jsを導入することで、Middlewareでブロックする前後のアクセス状況を計測できます。ブロック効果をデータで確認しながら運用できます。