www/middleware2.ts
Xe Iaso d74a20181a
rname thing
Signed-off-by: Xe Iaso <me@xeiaso.net>
2024-09-28 17:56:11 -04:00

40 lines
1.2 KiB
TypeScript

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 decision = await aj.protect(request);
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();
}
}