import arcjet, { detectBot } from "@arcjet/next"; import { NextRequest, NextResponse } from "next/server"; export const config = { // matcher tells Next.js which routes to run the middleware on. // This runs the middleware on all routes except for static assets. matcher: ["/((?!_next/static|_next/image|favicon.ico|healthz|.well-known/.*).*)"], }; const aj = arcjet({ key: process.env.ARCJET_KEY!, rules: [ detectBot({ mode: "LIVE", allow: [ "CATEGORY:SEARCH_ENGINE", "CATEGORY:PREVIEW", "CATEGORY:SOCIAL", "GO_HTTP", ], }), ], }); export default async function middleware(req: NextRequest) { const decision = await aj.protect(req); if ( decision.isDenied() && decision.reason.isBot() ) { return NextResponse.json({ error: "Unauthorized" }, { status: 403 }); } else if (decision.isErrored()) { console.warn("Arcjet error", decision.reason.message); return NextResponse.json({ error: "Bad request" }, { status: 400 }); } else { return NextResponse.next(); } }