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).*)"], }; const aj = arcjet({ key: process.env.ARCJET_KEY!, rules: [ detectBot({ mode: "LIVE", allow: [ "CATEGORY:SEARCH_ENGINE", "CATEGORY:PREVIEW", "CATEGORY:SOCIAL", ], }), ], }); export default async function middleware(request: NextRequest) { const req = { ...request, ip: request.headers.get("x-real-ip"), } as NextRequest; console.log(req.ip); const decision = await aj.protect(req); if ( // If this deny comes from a bot rule then block the request. You can // customize this logic to fit your needs e.g. changing the status code. 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(); } }