Bot protection reference
Arcjet bot detection allows you to manage traffic by automated clients and bots.
Plan availability
Arcjet bot detection functionality depends on your pricing plan.
Plan | Bot protection |
---|---|
Free | Basic - user agent + IP type analysis |
Pro | Advanced - IP reputation, verification, and other signals |
Enterprise | Custom |
Configuration
Bot detection is configured by allowing or denying a subset of bots. The allow
and deny
lists are mutually-exclusive, such that using allow
will result in
a DENY
decision for any detected bot that is not specified in the allow
list
and using deny
will result in an ALLOW
decision for any detected bot that is
not specified in the deny
list.
You can use only one of the following configuration definitions:
type BotOptionsAllow = { mode?: "LIVE" | "DRY_RUN"; allow: Array<ArcjetWellKnownBot | ArcjetBotCategory>;};
type BotOptionsDeny = { mode?: "LIVE" | "DRY_RUN"; deny: Array<ArcjetWellKnownBot | ArcjetBotCategory>;};
The arcjet
client is configured with one or more detectBot
rules which take
one or many BotOptions
.
Allowing specific bots
Most applications want to block almost all bots. However, it is common to allow some bots to access your system, such as bots for search indexing or API access from the command line.
When allowing specific bots we recommend that you also check the verification status after an allow decision is returned to ensure that the bots are who they say they are.
This behavior is configured with an allow
list from our full list of
bots and/or bot
categories.
import { detectBot } from "@arcjet/nest";// ...// This is part of the rules constructed using withRule or a guard// ...detectBot({ mode: "LIVE", // configured with a list of bots to allow from // https://arcjet.com/bot-list - all other detected bots will be blocked allow: [ // Google has multiple crawlers, each with a different user-agent, so we // allow the entire Google category "CATEGORY:GOOGLE", "CURL", // allows the default user-agent of the `curl` tool "DISCORD_CRAWLER", // allows Discordbot ],});
import arcjet, { detectBot } from "@arcjet/node";
const aj = arcjet({ key: process.env.ARCJET_KEY!, rules: [ detectBot({ mode: "LIVE", // configured with a list of bots to allow from // https://arcjet.com/bot-list - all other detected bots will be blocked allow: [ // Google has multiple crawlers, each with a different user-agent, so we // allow the entire Google category "CATEGORY:GOOGLE", "CURL", // allows the default user-agent of the `curl` tool "DISCORD_CRAWLER", // allows Discordbot ], }), ],});
import arcjet, { detectBot } from "@arcjet/node";
const aj = arcjet({ key: process.env.ARCJET_KEY, rules: [ detectBot({ mode: "LIVE", // configured with a list of bots to allow from // https://arcjet.com/bot-list - all other detected bots will be blocked allow: [ // Google has multiple crawlers, each with a different user-agent, so we // allow the entire Google category "CATEGORY:GOOGLE", "CURL", // allows the default user-agent of the `curl` tool "DISCORD_CRAWLER", // allows Discordbot ], }), ],});
import arcjet, { detectBot } from "@arcjet/bun";import { env } from "bun";
const aj = arcjet({ key: env.ARCJET_KEY!, // Get your site key from https://app.arcjet.com rules: [ detectBot({ mode: "LIVE", // configured with a list of bots to allow from // https://arcjet.com/bot-list - all other detected bots will be blocked allow: [ // Google has multiple crawlers, each with a different user-agent, so we // allow the entire Google category "CATEGORY:GOOGLE", "CURL", // allows the default user-agent of the `curl` tool "DISCORD_CRAWLER", // allows Discordbot ], }), ],});
export default { port: 3000, fetch: aj.handler(async (req) => { const decision = await aj.protect(req);
if (decision.isDenied()) { // Bots not in the allow list will be blocked if (decision.reason.isBot()) { return new Response("You are a bot!", { status: 403 }); } else { return new Response("Forbidden", { status: 403 }); } }
for (const { state, reason } of decision.results) { if (state === "DRY_RUN") { continue; }
// Arcjet Pro plan verifies the authenticity of common bots using IP data. // https://docs.arcjet.com/bot-protection/reference#bot-verification if (reason.isBot() && reason.isSpoofed()) { return new Response("You are pretending to be a good bot!", { status: 403, }); } }
return new Response("Hello world"); }),};
import arcjet, { detectBot } from "@arcjet/bun";import { env } from "bun";
const aj = arcjet({ key: env.ARCJET_KEY, // Get your site key from https://app.arcjet.com rules: [ detectBot({ mode: "LIVE", // configured with a list of bots to allow from // https://arcjet.com/bot-list - all other detected bots will be blocked allow: [ // Google has multiple crawlers, each with a different user-agent, so we // allow the entire Google category "CATEGORY:GOOGLE", "CURL", // allows the default user-agent of the `curl` tool "DISCORD_CRAWLER", // allows Discordbot ], }), ],});
export default { port: 3000, fetch: aj.handler(async (req) => { const decision = await aj.protect(req);
if (decision.isDenied()) { if (decision.reason.isBot()) { // Bots not in the allow list will be blocked return new Response("You are a bot!", { status: 403 }); } else { return new Response("Forbidden", { status: 403 }); } }
for (const { state, reason } of decision.results) { if (state === "DRY_RUN") { continue; }
// Arcjet Pro plan verifies the authenticity of common bots using IP data. // https://docs.arcjet.com/bot-protection/reference#bot-verification if (reason.isBot() && reason.isSpoofed()) { return new Response("You are pretending to be a good bot!", { status: 403, }); } }
return new Response("Hello world"); }),};
import arcjet, { detectBot } from "@arcjet/deno";
const aj = arcjet({ key: Deno.env.get("ARCJET_KEY")!, // Get your site key from https://app.arcjet.com rules: [ detectBot({ mode: "LIVE", // configured with a list of bots to allow from // https://arcjet.com/bot-list - all other detected bots will be blocked allow: [ // Google has multiple crawlers, each with a different user-agent, so we // allow the entire Google category "CATEGORY:GOOGLE", "CURL", // allows the default user-agent of the `curl` tool "DISCORD_CRAWLER", // allows Discordbot ], }), ],});
Deno.serve( { port: 3000 }, aj.handler(async (req) => { const decision = await aj.protect(req);
if (decision.isDenied()) { // Bots not in the allow list will be blocked if (decision.reason.isBot()) { return new Response("You are a bot!", { status: 403 }); } else { return new Response("Forbidden", { status: 403 }); } }
for (const { state, reason } of decision.results) { if (state === "DRY_RUN") { continue; }
// Arcjet Pro plan verifies the authenticity of common bots using IP data. // https://docs.arcjet.com/bot-protection/reference#bot-verification if (reason.isBot() && reason.isSpoofed()) { return new Response("You are pretending to be a good bot!", { status: 403, }); } }
return new Response("Hello world"); }),);
import arcjet, { detectBot } from "@arcjet/next";
const aj = arcjet({ key: process.env.ARCJET_KEY, rules: [ detectBot({ mode: "LIVE", // configured with a list of bots to allow from // https://arcjet.com/bot-list - all other detected bots will be blocked allow: [ // Google has multiple crawlers, each with a different user-agent, so we // allow the entire Google category "CATEGORY:GOOGLE", "CURL", // allows the default user-agent of the `curl` tool "DISCORD_CRAWLER", // allows Discordbot ], }), ],});
export default async function handler(req, res) { const decision = await aj.protect(req);
if (decision.isDenied()) { // Bots not in the allow list will be blocked if (decision.reason.isBot()) { return res.status(403).json({ error: "You are a bot!", // Useful for debugging, but don't return these to the client in // production denied: decision.reason.denied, }); } else { return res.status(403).json({ error: "Forbidden", }); } }
for (const { state, reason } of decision.results) { if (state === "DRY_RUN") { continue; }
// Arcjet Pro plan verifies the authenticity of common bots using IP data. // https://docs.arcjet.com/bot-protection/reference#bot-verification if (reason.isBot() && reason.isSpoofed()) { return res.status(403).json({ error: "You are pretending to be a good bot!", }); } }
res.status(200).json({ name: "Hello world" });}
import arcjet, { detectBot } from "@arcjet/next";
const aj = arcjet({ key: process.env.ARCJET_KEY, rules: [ detectBot({ mode: "LIVE", // configured with a list of bots to allow from // https://arcjet.com/bot-list - all other detected bots will be blocked allow: [ // Google has multiple crawlers, each with a different user-agent, so we // allow the entire Google category "CATEGORY:GOOGLE", "CURL", // allows the default user-agent of the `curl` tool "DISCORD_CRAWLER", // allows Discordbot ], }), ],});
export default async function handler(req, res) { const decision = await aj.protect(req);
if (decision.isDenied()) { // Bots not in the allow list will be blocked if (decision.reason.isBot()) { return res.status(403).json({ error: "You are a bot!", // Useful for debugging, but don't return these to the client in // production denied: decision.reason.denied, }); } else { return res.status(403).json({ error: "Forbidden", }); } }
for (const { state, reason } of decision.results) { if (state === "DRY_RUN") { continue; }
// Arcjet Pro plan verifies the authenticity of common bots using IP data. // https://docs.arcjet.com/bot-protection/reference#bot-verification if (reason.isBot() && reason.isSpoofed()) { return res.status(403).json({ error: "You are pretending to be a good bot!", }); } }
res.status(200).json({ name: "Hello world" });}
import arcjet, { detectBot } from "@arcjet/next";import { NextResponse } from "next/server";
const aj = arcjet({ key: process.env.ARCJET_KEY!, rules: [ detectBot({ mode: "LIVE", // configured with a list of bots to allow from // https://arcjet.com/bot-list - all other detected bots will be blocked allow: [ // Google has multiple crawlers, each with a different user-agent, so we // allow the entire Google category "CATEGORY:GOOGLE", "CURL", // allows the default user-agent of the `curl` tool "DISCORD_CRAWLER", // allows Discordbot ], }), ],});
export async function POST(req: Request) { const decision = await aj.protect(req);
if (decision.isDenied()) { // Bots not in the allow list will be blocked if (decision.reason.isBot()) { return NextResponse.json( { error: "You are a bot!", // Useful for debugging, but don't return these to the client in // production denied: decision.reason.denied, }, { status: 403 }, ); } else { return NextResponse.json({ error: "Forbidden" }, { status: 403 }); } }
for (const { state, reason } of decision.results) { if (state === "DRY_RUN") { continue; }
// Arcjet Pro plan verifies the authenticity of common bots using IP data. // https://docs.arcjet.com/bot-protection/reference#bot-verification if (reason.isBot() && reason.isSpoofed()) { return NextResponse.json( { error: "You are pretending to be a good bot!" }, { status: 403 }, ); } }
return NextResponse.json({ message: "Hello world", });}
import arcjet, { detectBot } from "@arcjet/next";import type { NextApiRequest, NextApiResponse } from "next";
const aj = arcjet({ key: process.env.ARCJET_KEY!, rules: [ detectBot({ mode: "LIVE", // configured with a list of bots to allow from // https://arcjet.com/bot-list - all other detected bots will be blocked allow: [ // Google has multiple crawlers, each with a different user-agent, so we // allow the entire Google category "CATEGORY:GOOGLE", "CURL", // allows the default user-agent of the `curl` tool "DISCORD_CRAWLER", // allows Discordbot ], }), ],});
export default async function handler( req: NextApiRequest, res: NextApiResponse,) { const decision = await aj.protect(req);
if (decision.isDenied()) { // Bots not in the allow list will be blocked if (decision.reason.isBot()) { return res.status(403).json({ error: "You are a bot!", // Useful for debugging, but don't return these to the client in // production denied: decision.reason.denied, }); } else { return res.status(403).json({ error: "Forbidden", }); } }
for (const { state, reason } of decision.results) { if (state === "DRY_RUN") { continue; }
// Arcjet Pro plan verifies the authenticity of common bots using IP data. // https://docs.arcjet.com/bot-protection/reference#bot-verification if (reason.isBot() && reason.isSpoofed()) { return res.status(403).json({ error: "You are pretending to be a good bot!", }); } }
res.status(200).json({ name: "Hello world" });}
import arcjet, { detectBot } from "@arcjet/remix";import type { LoaderFunctionArgs } from "@remix-run/node";
const aj = arcjet({ key: process.env.ARCJET_KEY!, rules: [ detectBot({ mode: "LIVE", // configured with a list of bots to allow from // https://arcjet.com/bot-list - all other detected bots will be blocked allow: [ // Google has multiple crawlers, each with a different user-agent, so we // allow the entire Google category "CATEGORY:GOOGLE", "CURL", // allows the default user-agent of the `curl` tool "DISCORD_CRAWLER", // allows Discordbot ], }), ],});
export async function loader(args: LoaderFunctionArgs) { const decision = await aj.protect(args);
if (decision.isDenied()) { // Bots not in the allow list will be blocked if (decision.reason.isBot()) { throw new Response("You are a bot!", { status: 403, statusText: "Forbidden", }); } else { throw new Response("Forbidden", { status: 403, statusText: "Forbidden", }); } }
for (const { state, reason } of decision.results) { if (state === "DRY_RUN") { continue; }
// Arcjet Pro plan verifies the authenticity of common bots using IP data. // https://docs.arcjet.com/bot-protection/reference#bot-verification if (reason.isBot() && reason.isSpoofed()) { throw new Response("You are pretending to be a good bot!", { status: 403, statusText: "Forbidden", }); } }
return null;}
import arcjet, { detectBot } from "@arcjet/remix";
const aj = arcjet({ key: process.env.ARCJET_KEY, rules: [ detectBot({ mode: "LIVE", // configured with a list of bots to allow from // https://arcjet.com/bot-list - all other detected bots will be blocked allow: [ // Google has multiple crawlers, each with a different user-agent, so we // allow the entire Google category "CATEGORY:GOOGLE", "CURL", // allows the default user-agent of the `curl` tool "DISCORD_CRAWLER", // allows Discordbot ], }), ],});
export async function loader(args) { const decision = await aj.protect(args);
if (decision.isDenied()) { // Bots not in the allow list will be blocked if (decision.reason.isBot()) { throw new Response("You are a bot!", { status: 403, statusText: "Forbidden", }); } else { throw new Response("Forbidden", { status: 403, statusText: "Forbidden", }); } }
for (const { state, reason } of decision.results) { if (state === "DRY_RUN") { continue; }
// Arcjet Pro plan verifies the authenticity of common bots using IP data. // https://docs.arcjet.com/bot-protection/reference#bot-verification if (reason.isBot() && reason.isSpoofed()) { throw new Response("You are pretending to be a good bot!", { status: 403, statusText: "Forbidden", }); } }
return null;}
import { env } from "$env/dynamic/private";import arcjet, { detectBot } from "@arcjet/sveltekit";import { error } from "@sveltejs/kit";
const aj = arcjet({ key: env.ARCJET_KEY, // Get your site key from https://app.arcjet.com rules: [ detectBot({ mode: "LIVE", // configured with a list of bots to allow from // https://arcjet.com/bot-list - all other detected bots will be blocked allow: [ // Google has multiple crawlers, each with a different user-agent, so we // allow the entire Google category "CATEGORY:GOOGLE", "CURL", // allows the default user-agent of the `curl` tool "DISCORD_CRAWLER", // allows Discordbot ], }), ],});
export async function handle({ event, resolve }) { const decision = await aj.protect(event);
if (decision.isDenied()) { // Bots not in the allow list will be blocked if (decision.reason.isBot()) { return error(403, "You are a bot!"); } else { return error(403, "Forbidden"); } }
for (const { state, reason } of decision.results) { if (state === "DRY_RUN") { continue; }
// Arcjet Pro plan verifies the authenticity of common bots using IP data. // https://docs.arcjet.com/bot-protection/reference#bot-verification if (reason.isBot() && reason.isSpoofed()) { return error(403, "You are pretending to be a good bot!"); } }
return resolve(event);}
import { env } from "$env/dynamic/private";import arcjet, { detectBot } from "@arcjet/sveltekit";import { error, type RequestEvent } from "@sveltejs/kit";
const aj = arcjet({ key: env.ARCJET_KEY!, // Get your site key from https://app.arcjet.com rules: [ detectBot({ mode: "LIVE", // configured with a list of bots to allow from // https://arcjet.com/bot-list - all other detected bots will be blocked allow: [ // Google has multiple crawlers, each with a different user-agent, so we // allow the entire Google category "CATEGORY:GOOGLE", "CURL", // allows the default user-agent of the `curl` tool "DISCORD_CRAWLER", // allows Discordbot ], }), ],});
export async function handle({ event, resolve,}: { event: RequestEvent; resolve: (event: RequestEvent) => Response | Promise<Response>;}): Promise<Response> { const decision = await aj.protect(event);
if (decision.isDenied()) { // Bots not in the allow list will be blocked if (decision.reason.isBot()) { return error(403, "You are a bot!"); } else { return error(403, "Forbidden"); } }
for (const { state, reason } of decision.results) { if (state === "DRY_RUN") { continue; }
// Arcjet Pro plan verifies the authenticity of common bots using IP data. // https://docs.arcjet.com/bot-protection/reference#bot-verification if (reason.isBot() && reason.isSpoofed()) { return error(403, "You are pretending to be a good bot!"); } }
return resolve(event);}
Denying specific bots
Some applications may only want to block a small subset of bots, while allowing the majority continued access. This may be due to many reasons, such as misconfigured or high-traffic bots.
This behavior is configured with a deny
list from our full list of
bots and/or bot
categories.
import { detectBot } from "@arcjet/nest";// ...// This is part of the rules constructed using withRule or a guard// ...detectBot({ mode: "LIVE", // configured with a list of bots to deny from // https://arcjet.com/bot-list - all other detected bots will be allowed deny: [ "CATEGORY:AI", // denies all detected AI and LLM scrapers "CURL", // denies the default user-agent of the `curl` tool ],});
import arcjet, { detectBot } from "@arcjet/node";
const aj = arcjet({ key: process.env.ARCJET_KEY!, rules: [ detectBot({ mode: "LIVE", // configured with a list of bots to deny from // https://arcjet.com/bot-list - all other detected bots will be allowed deny: [ "CATEGORY:AI", // denies all detected AI and LLM scrapers "CURL", // denies the default user-agent of the `curl` tool ], }), ],});
import arcjet, { detectBot } from "@arcjet/node";
const aj = arcjet({ key: process.env.ARCJET_KEY, rules: [ detectBot({ mode: "LIVE", // configured with a list of bots to deny from // https://arcjet.com/bot-list - all other detected bots will be allowed deny: [ "CATEGORY:AI", // denies all detected AI and LLM scrapers "CURL", // denies the default user-agent of the `curl` tool ], }), ],});
import arcjet, { detectBot } from "@arcjet/bun";import { env } from "bun";
const aj = arcjet({ key: env.ARCJET_KEY!, // Get your site key from https://app.arcjet.com rules: [ detectBot({ mode: "LIVE", // configured with a list of bots to deny from // https://arcjet.com/bot-list - all other detected bots will be allowed deny: [ "CATEGORY:AI", // denies all detected AI and LLM scrapers "CURL", // denies the default user-agent of the `curl` tool ], }), ],});
export default { port: 3000, fetch: aj.handler(async (req) => { const decision = await aj.protect(req);
if (decision.isDenied()) { return new Response("Forbidden", { status: 403 }); }
return new Response("Hello world"); }),};
import arcjet, { detectBot } from "@arcjet/bun";import { env } from "bun";
const aj = arcjet({ key: env.ARCJET_KEY, // Get your site key from https://app.arcjet.com rules: [ detectBot({ mode: "LIVE", // configured with a list of bots to deny from // https://arcjet.com/bot-list - all other detected bots will be allowed deny: [ "CATEGORY:AI", // denies all detected AI and LLM scrapers "CURL", // denies the default user-agent of the `curl` tool ], }), ],});
export default { port: 3000, fetch: aj.handler(async (req) => { const decision = await aj.protect(req);
if (decision.isDenied()) { return new Response("Forbidden", { status: 403 }); }
return new Response("Hello world"); }),};
import arcjet, { detectBot } from "@arcjet/deno";
const aj = arcjet({ key: Deno.env.get("ARCJET_KEY")!, // Get your site key from https://app.arcjet.com rules: [ detectBot({ mode: "LIVE", // configured with a list of bots to deny from // https://arcjet.com/bot-list - all other detected bots will be allowed deny: [ "CATEGORY:AI", // denies all detected AI and LLM scrapers "CURL", // denies the default user-agent of the `curl` tool ], }), ],});
Deno.serve( { port: 3000 }, aj.handler(async (req) => { const decision = await aj.protect(req);
if (decision.isDenied()) { return new Response("Forbidden", { status: 403 }); }
return new Response("Hello world"); }),);
import arcjet, { detectBot } from "@arcjet/remix";import type { LoaderFunctionArgs } from "@remix-run/node";
const aj = arcjet({ key: process.env.ARCJET_KEY!, rules: [ detectBot({ mode: "LIVE", // configured with a list of bots to deny from // https://arcjet.com/bot-list - all other detected bots will be allowed deny: [ "CATEGORY:AI", // denies all detected AI and LLM scrapers "CURL", // denies the default user-agent of the `curl` tool ], }), ],});
export async function loader(args: LoaderFunctionArgs) { const decision = await aj.protect(args);
if (decision.isDenied()) { throw new Response("Forbidden", { status: 403, statusText: "Forbidden" }); }
return null;}
import arcjet, { detectBot } from "@arcjet/remix";
const aj = arcjet({ key: process.env.ARCJET_KEY, rules: [ detectBot({ mode: "LIVE", // configured with a list of bots to deny from // https://arcjet.com/bot-list - all other detected bots will be allowed deny: [ "CATEGORY:AI", // denies all detected AI and LLM scrapers "CURL", // denies the default user-agent of the `curl` tool ], }), ],});
export async function loader(args) { const decision = await aj.protect(args);
if (decision.isDenied()) { throw new Response("Forbidden", { status: 403, statusText: "Forbidden" }); }
return null;}
import arcjet, { detectBot } from "@arcjet/next";import { NextResponse } from "next/server";
const aj = arcjet({ key: process.env.ARCJET_KEY!, rules: [ detectBot({ mode: "LIVE", // configured with a list of bots to deny from // https://arcjet.com/bot-list - all other detected bots will be allowed deny: [ "CATEGORY:AI", // denies all detected AI and LLM scrapers "CURL", // denies the default user-agent of the `curl` tool ], }), ],});
export async function POST(req: Request) { const decision = await aj.protect(req);
if (decision.isDenied() && decision.reason.isBot()) { return NextResponse.json( { error: "You are a bot!", // Useful for debugging, but don't return these to the client in // production denied: decision.reason.denied, }, { status: 403 }, ); }
return NextResponse.json({ message: "Hello world", });}
import arcjet, { detectBot } from "@arcjet/next";import type { NextApiRequest, NextApiResponse } from "next";
const aj = arcjet({ key: process.env.ARCJET_KEY!, rules: [ detectBot({ mode: "LIVE", // configured with a list of bots to deny from // https://arcjet.com/bot-list - all other detected bots will be allowed deny: [ "CATEGORY:AI", // denies all detected AI and LLM scrapers "CURL", // denies the default user-agent of the `curl` tool ], }), ],});
export default async function handler( req: NextApiRequest, res: NextApiResponse,) { const decision = await aj.protect(req); console.log("Decision", decision);
if (decision.isDenied() && decision.reason.isBot()) { return res.status(403).json({ error: "Forbidden", // Useful for debugging, but don't return these to the client in // production denied: decision.reason.denied, }); }
res.status(200).json({ name: "Hello world" });}
import arcjet, { detectBot } from "@arcjet/next";import { NextResponse } from "next/server";
const aj = arcjet({ key: process.env.ARCJET_KEY, rules: [ detectBot({ mode: "LIVE", // configured with a list of bots to deny from // https://arcjet.com/bot-list - all other detected bots will be allowed deny: [ "CATEGORY:AI", // denies all detected AI and LLM scrapers "CURL", // denies the default user-agent of the `curl` tool ], }), ],});
export async function POST(req) { const decision = await aj.protect(req);
if (decision.isDenied() && decision.reason.isBot()) { return NextResponse.json( { error: "You are a bot!", // Useful for debugging, but don't return these to the client in // production denied: decision.reason.denied, }, { status: 403 }, ); }
return NextResponse.json({ message: "Hello world", });}
import arcjet, { detectBot } from "@arcjet/next";import type { NextApiRequest, NextApiResponse } from "next";
const aj = arcjet({ key: process.env.ARCJET_KEY!, rules: [ detectBot({ mode: "LIVE", // configured with a list of bots to deny from // https://arcjet.com/bot-list - all other detected bots will be allowed deny: [ "CATEGORY:AI", // denies all detected AI and LLM scrapers "CURL", // denies the default user-agent of the `curl` tool ], }), ],});
export default async function handler( req: NextApiRequest, res: NextApiResponse,) { const decision = await aj.protect(req); console.log("Decision", decision);
if (decision.isDenied() && decision.reason.isBot()) { return res.status(403).json({ error: "Forbidden", // Useful for debugging, but don't return these to the client in // production denied: decision.reason.denied, }); }
res.status(200).json({ name: "Hello world" });}
import { env } from "$env/dynamic/private";import arcjet, { detectBot } from "@arcjet/sveltekit";import { error } from "@sveltejs/kit";
const aj = arcjet({ key: env.ARCJET_KEY, // Get your site key from https://app.arcjet.com rules: [ detectBot({ mode: "LIVE", // configured with a list of bots to deny from // https://arcjet.com/bot-list - all other detected bots will be allowed deny: [ "CATEGORY:AI", // denies all detected AI and LLM scrapers "CURL", // denies the default user-agent of the `curl` tool ], }), ],});
export async function handle({ event, resolve }) { const decision = await aj.protect(event);
if (decision.isDenied()) { return error(403, "You are a bot!"); }
return resolve(event);}
import { env } from "$env/dynamic/private";import arcjet, { detectBot } from "@arcjet/sveltekit";import { error, type RequestEvent } from "@sveltejs/kit";
const aj = arcjet({ key: env.ARCJET_KEY!, // Get your site key from https://app.arcjet.com rules: [ detectBot({ mode: "LIVE", // configured with a list of bots to deny from // https://arcjet.com/bot-list - all other detected bots will be allowed deny: [ "CATEGORY:AI", // denies all detected AI and LLM scrapers "CURL", // denies the default user-agent of the `curl` tool ], }), ],});
export async function handle({ event, resolve,}: { event: RequestEvent; resolve: (event: RequestEvent) => Response | Promise<Response>;}): Promise<Response> { const decision = await aj.protect(event);
if (decision.isDenied()) { return error(403, "You are a bot!"); }
return resolve(event);}
Loader vs action
Remix does not support middleware, instead they recommend calling functions directly inside the loader. Loaders execute before the page is loaded.
All our examples use this pattern, but you can also execute Arcjet in an
action. This would be appropriate
to protect a form submission or other non-GET
request.
For example, you might want to run rate limiting on every GET
page load, but
use rate limiting and email validation in an action handling a form POST
.
Action
This example shows how to run Arcjet in a Remix action:
import arcjet, { detectBot } from "@arcjet/remix";import type { ActionFunctionArgs } from "@remix-run/node";import { redirect } from "@remix-run/node";
const aj = arcjet({ key: process.env.ARCJET_KEY!, rules: [ detectBot({ mode: "LIVE", // configured with a list of bots to allow from // https://arcjet.com/bot-list - all other detected bots will be blocked allow: [ // Google has multiple crawlers, each with a different user-agent, so we // allow the entire Google category "CATEGORY:GOOGLE", "CURL", // allows the default user-agent of the `curl` tool "DISCORD_CRAWLER", // allows Discordbot ], }), ],});
export async function action(args: ActionFunctionArgs) { const decision = await aj.protect(args);
if (decision.isDenied()) { // This redirects to a generic error page (which you should create), but you // could also throw an error return redirect(`/error`); }
// ... // Process the action here // ...
return null;}
import arcjet, { detectBot } from "@arcjet/remix";import { redirect } from "@remix-run/node";
const aj = arcjet({ key: process.env.ARCJET_KEY, rules: [ detectBot({ mode: "LIVE", // configured with a list of bots to allow from // https://arcjet.com/bot-list - all other detected bots will be blocked allow: [ // Google has multiple crawlers, each with a different user-agent, so we // allow the entire Google category "CATEGORY:GOOGLE", "CURL", // allows the default user-agent of the `curl` tool "DISCORD_CRAWLER", // allows Discordbot ], }), ],});
export async function action(args) { const decision = await aj.protect(args);
if (decision.isDenied()) { // This redirects to a generic error page (which you should create), but you // could also throw an error return redirect(`/error`); }
// ... // Process the action here // ...
return null;}
Guards and routes
Arcjet can be integrated into NestJS in several places using NestJS guards or directly within the route controller:
- Global guard: Applies Arcjet rules on every request, but does not allow you to configure rules per route.
- Per route guard: Allows you to configure rules per route, but requires you to add the guard to every route and has limited flexibility.
- Within route: Requires some code duplication, but allows maximum flexibility because you can customize the rules and response.
Global guard
A global guard can be configured in src/app.module.ts
.
import { ArcjetModule, detectBot } from "@arcjet/nest";import { Module } from "@nestjs/common";import { ConfigModule } from "@nestjs/config";
@Module({ imports: [ ConfigModule.forRoot({ isGlobal: true, envFilePath: ".env.local", }), ArcjetModule.forRoot({ isGlobal: true, key: process.env.ARCJET_KEY!, rules: [ // Applies to every request detectBot({ mode: "LIVE", // configured with a list of bots to allow from // https://arcjet.com/bot-list - all other detected bots will be blocked allow: [ "CATEGORY:SEARCH_ENGINE", // Google, Bing, etc // Uncomment to allow these other common bot categories // See the full list at https://arcjet.com/bot-list //"CATEGORY:MONITOR", // Uptime monitoring services //"CATEGORY:PREVIEW", // Link previews e.g. Slack, Discord ], }), ], }), // ... other modules ],})export class AppModule {}
This can then be added to the controller for all the routes you wish to protect with Arcjet.
import { ArcjetGuard } from "@arcjet/nest";import { Controller, Get, Injectable, UseGuards } from "@nestjs/common";
// This would normally go in your controller file e.g.// src/page/page.controller.ts@Controller("page")// Uses the ArcjetGuard to protect the controller with the default rules defined// in app.module.ts. Using a guard makes it easy to apply Arcjet rules, but you// don't get access to the decision.@UseGuards(ArcjetGuard)export class PageController { constructor(private readonly pageService: PageService) {}
@Get() index() { return this.pageService.message(); }}
// This would normally go in your service file e.g.// src/page/page.service.ts@Injectable()export class PageService { message(): { message: string } { return { message: "Hello world", }; }}
Per route guard
A per route guard can be configured in the controller for each route you wish to
protect with specific Arcjet rules. The client created in src/app.module.ts
is automatically passed to the guard.
The rules will be applied and a generic error returned if the result is DENY
.
import { WithArcjetRules, detectBot } from "@arcjet/nest";import { Injectable, Get } from "@nestjs/common";
// This would normally go in your controller file e.g.// src/page/page.controller.ts// Attaches the ArcjetGuard to the controller to protect it with the specified// rules extended from the global rules defined in app.module.ts.@WithArcjetRules([ detectBot({ mode: "LIVE", // will block requests. Use "DRY_RUN" to log only // configured with a list of bots to allow from // https://arcjet.com/bot-list allow: [], // blocks all automated clients }),])export class PageController { constructor(private readonly pageService: PageService) {}
@Get() index() { return this.pageService.message(); }}
// This would normally go in your service file e.g.// src/page/page.service.ts@Injectable()export class PageService { message(): { message: string } { return { message: "Hello world", }; }}
Within route
Call Arcjet from within the route controller to have maximum flexibility.
import { ARCJET, type ArcjetNest, ArcjetRuleResult, detectBot,} from "@arcjet/nest";import { Controller, Get, HttpException, HttpStatus, Inject, Injectable, Req,} from "@nestjs/common";import type { Request } from "express";
function isSpoofed(result: ArcjetRuleResult) { return ( // You probably don't want DRY_RUN rules resulting in a denial // since they are generally used for evaluation purposes but you // could log here. result.state !== "DRY_RUN" && result.reason.isBot() && result.reason.isSpoofed() );}
// This would normally go in your service file e.g.// src/page/page.service.ts@Injectable()export class PageAdvancedService { message(): { message: string } { return { message: "Hello world", }; }}
// This would normally go in your controller file e.g.// src/page/page.controller.ts@Controller("page")// Sets up the Arcjet protection without using a guard so we can access the// decision and use it in the controller.export class PageAdvancedController { constructor( private readonly pageService: PageAdvancedService, @Inject(ARCJET) private readonly arcjet: ArcjetNest, ) {}
@Get() async index(@Req() req: Request) { const decision = await this.arcjet .withRule( detectBot({ mode: "LIVE", // will block requests. Use "DRY_RUN" to log only // configured with a list of bots to allow from // https://arcjet.com/bot-list allow: [], // blocks all automated clients }), ) .protect(req);
if (decision.isDenied()) { if (decision.reason.isBot()) { throw new HttpException("No bots allowed", HttpStatus.FORBIDDEN); } else { throw new HttpException("Forbidden", HttpStatus.FORBIDDEN); } }
// Arcjet Pro plan verifies the authenticity of common bots using IP data. // Verification isn't always possible, so we recommend checking the results // separately. // https://docs.arcjet.com/bot-protection/reference#bot-verification if (decision.results.some(isSpoofed)) { throw new HttpException("Forbidden", HttpStatus.FORBIDDEN); }
return this.pageService.message(); }}
Per route vs hooks
Bot protection rules can be configured in two ways:
- Per route: The rule is defined in the route handler itself. This allows you to configure the rule alongside the code it is protecting which is useful if you want to use the decision to add context to your own code. However, it means rules are not located in a single place.
- Hooks: The rule is defined as a hook. This allows you to configure rules in a single place or apply them globally to all routes, but it means the rules are not located alongside the code they are protecting.
Per route
This configures bot protection on a single route.
import { env } from "$env/dynamic/private";import arcjet, { detectBot } from "@arcjet/sveltekit";import { error, json, type RequestEvent } from "@sveltejs/kit";
const aj = arcjet({ key: env.ARCJET_KEY!, // Get your site key from https://app.arcjet.com rules: [ detectBot({ mode: "LIVE", allow: [], // "allow none" will block all detected bots }), ],});
export async function GET(event: RequestEvent) { const decision = await aj.protect(event);
if (decision.isDenied()) { return error(403, { message: "Forbidden" }); }
return json({ message: "Hello world" });}
import { env } from "$env/dynamic/private";import arcjet, { detectBot } from "@arcjet/sveltekit";import { error, json } from "@sveltejs/kit";
const aj = arcjet({ key: env.ARCJET_KEY, // Get your site key from https://app.arcjet.com rules: [ detectBot({ mode: "LIVE", allow: [], // "allow none" will block all detected bots }), ],});
export async function GET(event) { const decision = await aj.protect(event);
if (decision.isDenied()) { return error(403, { message: "Forbidden" }); }
return json({ message: "Hello world" });}
Hooks
This will run on every request to your SvelteKit app - see the SvelteKit Hooks docs for details.
import { env } from "$env/dynamic/private";import arcjet, { detectBot } from "@arcjet/sveltekit";import { error } from "@sveltejs/kit";
const aj = arcjet({ key: env.ARCJET_KEY, // Get your site key from https://app.arcjet.com rules: [ detectBot({ mode: "LIVE", // will block requests. Use "DRY_RUN" to log only // Block all bots except the following allow: [ "CATEGORY:SEARCH_ENGINE", // Google, Bing, etc // Uncomment to allow these other common bot categories // See the full list at https://arcjet.com/bot-list //"CATEGORY:MONITOR", // Uptime monitoring services //"CATEGORY:PREVIEW", // Link previews e.g. Slack, Discord ], }), ],});
function isSpoofed(result) { return ( // You probably don't want DRY_RUN rules resulting in a denial // since they are generally used for evaluation purposes but you // could log here. result.state !== "DRY_RUN" && result.reason.isBot() && result.reason.isSpoofed() );}
export async function handle({ event, resolve }) { const decision = await aj.protect(event);
// Bots not in the allow list will be blocked if (decision.isDenied()) { return error(403, "Forbidden"); }
// Arcjet Pro plan verifies the authenticity of common bots using IP data. // Verification isn't always possible, so we recommend checking the results // separately. // https://docs.arcjet.com/bot-protection/reference#bot-verification if (decision.results.some(isSpoofed)) { return error(403, "You are a bot!"); }
return resolve(event);}
import { env } from "$env/dynamic/private";import arcjet, { ArcjetRuleResult, detectBot } from "@arcjet/sveltekit";import { error, type RequestEvent } from "@sveltejs/kit";
const aj = arcjet({ key: env.ARCJET_KEY!, // Get your site key from https://app.arcjet.com rules: [ detectBot({ mode: "LIVE", // will block requests. Use "DRY_RUN" to log only // Block all bots except the following allow: [ "CATEGORY:SEARCH_ENGINE", // Google, Bing, etc // Uncomment to allow these other common bot categories // See the full list at https://arcjet.com/bot-list //"CATEGORY:MONITOR", // Uptime monitoring services //"CATEGORY:PREVIEW", // Link previews e.g. Slack, Discord ], }), ],});
function isSpoofed(result: ArcjetRuleResult) { return ( // You probably don't want DRY_RUN rules resulting in a denial // since they are generally used for evaluation purposes but you // could log here. result.state !== "DRY_RUN" && result.reason.isBot() && result.reason.isSpoofed() );}
export async function handle({ event, resolve,}: { event: RequestEvent; resolve: (event: RequestEvent) => Response | Promise<Response>;}): Promise<Response> { const decision = await aj.protect(event);
// Bots not in the allow list will be blocked if (decision.isDenied()) { return error(403, "Forbidden"); }
// Arcjet Pro plan verifies the authenticity of common bots using IP data. // Verification isn't always possible, so we recommend checking the results // separately. // https://docs.arcjet.com/bot-protection/reference#bot-verification if (decision.results.some(isSpoofed)) { return error(403, "You are a bot!"); }
return resolve(event);}
Avoiding double protection with hooks
If you use Arcjet in hooks and individual routes, you need to be careful that Arcjet is not running multiple times per request. This can be avoided by excluding the individual routes before running Arcjet in the hook.
For example, if you already have rules defined in the API route
at /api/arcjet
, you can exclude it from the hook like this:
import { env } from "$env/dynamic/private";import arcjet, { detectBot } from "@arcjet/sveltekit";import { error, type RequestEvent } from "@sveltejs/kit";
const aj = arcjet({ key: env.ARCJET_KEY!, rules: [ detectBot({ mode: "LIVE", allow: [], // "allow none" will block all detected bots }), ],});
export async function handle({ event, resolve,}: { event: RequestEvent; resolve: (event: RequestEvent) => Response | Promise<Response>;}): Promise<Response> { // Ignore routes that extend the Arcjet rules // - they will call `.protect` themselves const filteredRoutes = ["/api/arcjet"]; if (filteredRoutes.includes(event.url.pathname)) { // return - route will handle protecttion return resolve(event); }
const decision = await aj.protect(event);
if (decision.isDenied()) { return error(403, "Forbidden"); }
return resolve(event);}
Per route vs middleware
Bot protection rules can be configured in two ways:
- Per API route: The rule is defined in the API route itself. This allows you to configure the rule alongside the code it is protecting which is useful if you want to use the decision to add context to your own code. However, it means rules are not located in a single place.
- Middleware: The rule is defined in the middleware. This allows you to configure rules in a single place or apply them globally to all routes, but it means the rules are not located alongside the code they are protecting.
Per route
This configures bot protection on a single route.
import arcjet, { detectBot } from "@arcjet/next";
const aj = arcjet({ key: process.env.ARCJET_KEY, rules: [ detectBot({ mode: "LIVE", allow: [], // "allow none" will block all detected bots }), ],});
function isSpoofed(result) { return ( // You probably don't want DRY_RUN rules resulting in a denial // since they are generally used for evaluation purposes but you // could log here. result.state !== "DRY_RUN" && result.reason.isBot() && result.reason.isSpoofed() );}
export default async function handler(req, res) { const decision = await aj.protect(req);
if (decision.isDenied() && decision.reason.isBot()) { return res.status(403).json({ error: "You are a bot!" }); }
// Arcjet Pro plan verifies the authenticity of common bots using IP data. // Verification isn't always possible, so we recommend checking the results // separately. // https://docs.arcjet.com/bot-protection/reference#bot-verification if (decision.results.some(isSpoofed)) { return res.status(403).json({ error: "You are a bot!" }); }
res.status(200).json({ name: "Hello world" });}
import arcjet, { ArcjetRuleResult, detectBot } from "@arcjet/next";import type { NextApiRequest, NextApiResponse } from "next";
const aj = arcjet({ key: process.env.ARCJET_KEY!, rules: [ detectBot({ mode: "LIVE", allow: [], // "allow none" will block all detected bots }), ],});
function isSpoofed(result: ArcjetRuleResult) { return ( // You probably don't want DRY_RUN rules resulting in a denial // since they are generally used for evaluation purposes but you // could log here. result.state !== "DRY_RUN" && result.reason.isBot() && result.reason.isSpoofed() );}
export default async function handler( req: NextApiRequest, res: NextApiResponse,) { const decision = await aj.protect(req);
if (decision.isDenied() && decision.reason.isBot()) { return res.status(403).json({ error: "You are a bot!" }); }
// Arcjet Pro plan verifies the authenticity of common bots using IP data. // Verification isn't always possible, so we recommend checking the results // separately. // https://docs.arcjet.com/bot-protection/reference#bot-verification if (decision.results.some(isSpoofed)) { return res.status(403).json({ error: "You are a bot!" }); }
res.status(200).json({ name: "Hello world" });}
import arcjet, { ArcjetRuleResult, detectBot } from "@arcjet/next";import { NextResponse } from "next/server";
const aj = arcjet({ key: process.env.ARCJET_KEY!, rules: [ detectBot({ mode: "LIVE", allow: [], // "allow none" will block all detected bots }), ],});
function isSpoofed(result: ArcjetRuleResult) { return ( // You probably don't want DRY_RUN rules resulting in a denial // since they are generally used for evaluation purposes but you // could log here. result.state !== "DRY_RUN" && result.reason.isBot() && result.reason.isSpoofed() );}
export async function GET(req: Request) { const decision = await aj.protect(req);
if (decision.isDenied() && decision.reason.isBot()) { return NextResponse.json( { error: "You are a bot!", }, { status: 403 }, ); }
// Arcjet Pro plan verifies the authenticity of common bots using IP data. // Verification isn't always possible, so we recommend checking the results // separately. // https://docs.arcjet.com/bot-protection/reference#bot-verification if (decision.results.some(isSpoofed)) { return NextResponse.json( { error: "You are a bot!", }, { status: 403 }, ); }
return NextResponse.json({ message: "Hello world", });}
import arcjet, { detectBot } from "@arcjet/next";import { NextResponse } from "next/server";
const aj = arcjet({ key: process.env.ARCJET_KEY, rules: [ detectBot({ mode: "LIVE", allow: [], // "allow none" will block all detected bots }), ],});
function isSpoofed(result) { return ( // You probably don't want DRY_RUN rules resulting in a denial // since they are generally used for evaluation purposes but you // could log here. result.state !== "DRY_RUN" && result.reason.isBot() && result.reason.isSpoofed() );}
export async function GET(req) { const decision = await aj.protect(req);
if (decision.isDenied() && decision.reason.isBot()) { return NextResponse.json( { error: "You are a bot!", }, { status: 403 }, ); }
// Arcjet Pro plan verifies the authenticity of common bots using IP data. // Verification isn't always possible, so we recommend checking the results // separately. // https://docs.arcjet.com/bot-protection/reference#bot-verification if (decision.results.some(isSpoofed)) { return NextResponse.json( { error: "You are a bot!", }, { status: 403 }, ); }
return NextResponse.json({ message: "Hello world", });}
Middleware
This will run on every request to your Next.js app, except for static assets
(configured in the matcher
- see the Next.js
docs
for details).
Create a file called middleware.ts
in your project root (at the same level as
pages
or app
or inside src
):
import arcjet, { createMiddleware, detectBot } from "@arcjet/next";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!, // Get your site key from https://app.arcjet.com rules: [ detectBot({ mode: "LIVE", // will block requests. Use "DRY_RUN" to log only // Block all bots except the following allow: [ "CATEGORY:SEARCH_ENGINE", // Google, Bing, etc // Uncomment to allow these other common bot categories // See the full list at https://arcjet.com/bot-list //"CATEGORY:MONITOR", // Uptime monitoring services //"CATEGORY:PREVIEW", // Link previews e.g. Slack, Discord ], }), ],});// Pass any existing middleware with the optional existingMiddleware propexport default createMiddleware(aj);
You can also customize the response depending on the decision. In this case we will return a 403 Forbidden response only if we detect a hosting provider IP address for the bot detection rule result:
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!, // Get your site key from https://app.arcjet.com rules: [ detectBot({ mode: "LIVE", // will block requests. Use "DRY_RUN" to log only allow: [], // "allow none" will block all detected bots }), ],});
export default async function middleware(request: NextRequest) { const decision = await aj.protect(request);
if ( // If the decision is deny because the request is from a bot and the bot IP // address is from a known hosting provider, then block the request decision.isDenied() && decision.reason.isBot() && decision.ip.isHosting() ) { return NextResponse.json({ error: "Forbidden" }, { status: 403 }); } else { return NextResponse.next(); }}
Create a file called middleware.js
in your project root (at the same level as
pages
or app
or inside src
):
import arcjet, { createMiddleware, detectBot } from "@arcjet/next";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, // Get your site key from https://app.arcjet.com rules: [ detectBot({ mode: "LIVE", // will block requests. Use "DRY_RUN" to log only // Block all bots except the following allow: [ "CATEGORY:SEARCH_ENGINE", // Google, Bing, etc // Uncomment to allow these other common bot categories // See the full list at https://arcjet.com/bot-list //"CATEGORY:MONITOR", // Uptime monitoring services //"CATEGORY:PREVIEW", // Link previews e.g. Slack, Discord ], }), ],});// Pass any existing middleware with the optional existingMiddleware propexport default createMiddleware(aj);
You can also customize the response depending on the decision. In this case we will return a 403 Forbidden response only if we detect a hosting provider IP address for the bot detection rule result:
import arcjet, { detectBot } from "@arcjet/next";import { 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, // Get your site key from https://app.arcjet.com rules: [ detectBot({ mode: "LIVE", // will block requests. Use "DRY_RUN" to log only allow: [], // "allow none" will block all detected bots }), ],});
export default async function middleware(request) { const decision = await aj.protect(request);
if ( // If the decision is deny because the request is from a bot and the bot IP // address is from a known hosting provider, then block the request decision.isDenied() && decision.reason.isBot() && decision.ip.isHosting() ) { return NextResponse.json({ error: "Forbidden" }, { status: 403 }); } else { return NextResponse.next(); }}
Avoiding double protection with middleware
If you use Arcjet in middleware and individual routes, you need to be careful that Arcjet is not running multiple times per request. This can be avoided by excluding the API route from the middleware matcher.
For example, if you already have a bot detection rule defined in the API route
at /api/hello
, you can exclude it from the middleware by specifying a matcher
in /middleware.ts
:
import arcjet, { createMiddleware, detectBot } from "@arcjet/next";export const config = { // The matcher prevents the middleware executing on static assets and the // /api/hello API route because you already installed Arcjet directly matcher: ["/((?!_next/static|_next/image|favicon.ico|api/hello).*)"],};const aj = arcjet({ key: process.env.ARCJET_KEY!, rules: [ detectBot({ mode: "LIVE", allow: [], // "allow none" will block all detected bots }), ],});// Pass any existing middleware with the optional existingMiddleware propexport default createMiddleware(aj);
Pages & Server Actions
Arcjet can be used inside Next.js middleware, API routes, pages, server components, and server actions. Client components cannot be protected because they run on the client only.
See the Next.js SDK reference for examples of pages / page components and server actions.
Decision
The quick start example will deny requests that match the bot detection rules, immediately returning a response to the client.
Arcjet also provides a single protect
function that is used to execute your
protection rules. This requires a request
argument which is the request
context as passed to the request handler.
If you are using a global guard or per route
guard then protect
is called for you behind the scenes. If you add Arcjet
within a route then you call it directly.
This function returns a Promise
that resolves to an
ArcjetDecision
object. This contains the following properties:
id
(string
) - The unique ID for the request. This can be used to look up the request in the Arcjet dashboard. It is prefixed withreq_
for decisions involving the Arcjet cloud API. For decisions taken locally, the prefix islreq_
.conclusion
(ArcjetConclusion
) - The final conclusion based on evaluating each of the configured rules. If you wish to accept Arcjet’s recommended action based on the configured rules then you can use this property.reason
(ArcjetReason
) - An object containing more detailed information about the conclusion.results
(ArcjetRuleResult[]
) - An array ofArcjetRuleResult
objects containing the results of each rule that was executed.ip
(ArcjetIpDetails
) - An object containing Arcjet’s analysis of the client IP address. See the SDK reference for more information.
You check if a deny conclusion has been returned by a bot protection rule by
using decision.isDenied()
and decision.reason.isBot()
respectively.
You can iterate through the results and check whether a bot protection rule was applied:
for (const result of decision.results) { console.log("Rule Result", result);}
This example will log the results of each rule execution.
import arcjet, { detectBot, fixedWindow } from "@arcjet/deno";
const aj = arcjet({ key: Deno.env.get("ARCJET_KEY")!, // Get your site key from https://app.arcjet.com rules: [ fixedWindow({ mode: "LIVE", window: "1h", max: 60, }), detectBot({ mode: "LIVE", allow: [], // "allow none" will block all detected bots }), ],});
Deno.serve( { port: 3000 }, aj.handler(async (req) => { const decision = await aj.protect(req); console.log("Arcjet decision", decision);
for (const result of decision.results) { console.log("Rule Result", result);
if (result.reason.isRateLimit()) { console.log("Rate limit rule", result); }
if (result.reason.isBot()) { console.log("Bot protection rule", result); } }
if (decision.isDenied()) { return new Response("Forbidden", { status: 403 }); }
return new Response("Hello world"); }),);
This example will log the results of each rule execution.
import arcjet, { detectBot, fixedWindow } from "@arcjet/remix";import type { LoaderFunctionArgs } from "@remix-run/node";
const aj = arcjet({ key: process.env.ARCJET_KEY!, rules: [ fixedWindow({ mode: "LIVE", window: "1h", max: 60, }), detectBot({ mode: "LIVE", allow: [], // "allow none" will block all detected bots }), ],});
export async function loader(args: LoaderFunctionArgs) { const decision = await aj.protect(args);
for (const result of decision.results) { console.log("Rule Result", result);
if (result.reason.isRateLimit()) { console.log("Rate limit rule", result); }
if (result.reason.isBot()) { console.log("Bot protection rule", result); } }
if (decision.isDenied()) { throw new Response("Forbidden", { status: 403, statusText: "Forbidden" }); }
return null;}
import arcjet, { detectBot, fixedWindow } from "@arcjet/remix";
const aj = arcjet({ key: process.env.ARCJET_KEY, rules: [ fixedWindow({ mode: "LIVE", window: "1h", max: 60, }), detectBot({ mode: "LIVE", allow: [], // "allow none" will block all detected bots }), ],});
export async function loader(args) { const decision = await aj.protect(args);
for (const result of decision.results) { console.log("Rule Result", result);
if (result.reason.isRateLimit()) { console.log("Rate limit rule", result); }
if (result.reason.isBot()) { console.log("Bot protection rule", result); } }
if (decision.isDenied()) { throw new Response("Forbidden", { status: 403, statusText: "Forbidden" }); }
return null;}
This example will log the results of each rule execution.
import arcjet, { fixedWindow, detectBot } from "@arcjet/next";import { NextResponse } from "next/server";
const aj = arcjet({ key: process.env.ARCJET_KEY!, // Limiting by ip.src is the default if not specified //characteristics: ["ip.src"], rules: [ fixedWindow({ mode: "LIVE", window: "1h", max: 60, }), detectBot({ mode: "LIVE", allow: [], // "allow none" will block all detected bots }), ],});
export async function POST(req: Request) { const decision = await aj.protect(req);
for (const result of decision.results) { console.log("Rule Result", result);
if (result.reason.isRateLimit()) { console.log("Rate limit rule", result); }
if (result.reason.isBot()) { console.log("Bot protection rule", result); } }
if (decision.isDenied()) { return NextResponse.json({ error: "Forbidden" }, { status: 403 }); }
return NextResponse.json({ message: "Hello world", });}
import arcjet, { fixedWindow, detectBot } from "@arcjet/next";import { NextResponse } from "next/server";
const aj = arcjet({ key: process.env.ARCJET_KEY, // Limiting by ip.src is the default if not specified //characteristics: ["ip.src"], rules: [ fixedWindow({ mode: "LIVE", window: "1h", max: 60, }), detectBot({ mode: "LIVE", allow: [], // "allow none" will block all detected bots }), ],});
export async function POST(req) { const decision = await aj.protect(req);
for (const result of decision.results) { console.log("Rule Result", result);
if (result.reason.isRateLimit()) { console.log("Rate limit rule", result); }
if (result.reason.isBot()) { console.log("Bot protection rule", result); } }
if (decision.isDenied()) { return NextResponse.json({ error: "Forbidden" }, { status: 403 }); }
return NextResponse.json({ message: "Hello world", });}
import arcjet, { fixedWindow, detectBot } from "@arcjet/next";
const aj = arcjet({ key: process.env.ARCJET_KEY, // Limiting by ip.src is the default if not specified //characteristics: ["ip.src"], rules: [ fixedWindow({ mode: "LIVE", window: "1h", max: 60, }), detectBot({ mode: "LIVE", allow: [], // "allow none" will block all detected bots }), ],});
export default async function handler(req, res) { const decision = await aj.protect(req); console.log("Decision", decision);
for (const result of decision.results) { console.log("Rule Result", result);
if (result.reason.isRateLimit()) { console.log("Rate limit rule", result); }
if (result.reason.isBot()) { console.log("Bot protection rule", result); } }
if (decision.isDenied()) { return res .status(403) .json({ error: "Forbidden", reason: decision.reason }); }
res.status(200).json({ name: "Hello world" });}
import arcjet, { fixedWindow, detectBot } from "@arcjet/next";import type { NextApiRequest, NextApiResponse } from "next";
const aj = arcjet({ key: process.env.ARCJET_KEY!, // Limiting by ip.src is the default if not specified //characteristics: ["ip.src"], rules: [ fixedWindow({ mode: "LIVE", window: "1h", max: 60, }), detectBot({ mode: "LIVE", allow: [], // "allow none" will block all detected bots }), ],});
export default async function handler( req: NextApiRequest, res: NextApiResponse,) { const decision = await aj.protect(req); console.log("Decision", decision);
for (const result of decision.results) { console.log("Rule Result", result);
if (result.reason.isRateLimit()) { console.log("Rate limit rule", result); }
if (result.reason.isBot()) { console.log("Bot protection rule", result); } }
if (decision.isDenied()) { return res .status(403) .json({ error: "Forbidden", reason: decision.reason }); }
res.status(200).json({ name: "Hello world" });}
This example will log the results of each rule execution.
import { env } from "$env/dynamic/private";import arcjet, { detectBot, fixedWindow } from "@arcjet/sveltekit";import { error, json, type RequestEvent } from "@sveltejs/kit";
const aj = arcjet({ key: env.ARCJET_KEY!, // Get your site key from https://app.arcjet.com rules: [ fixedWindow({ mode: "LIVE", window: "1h", max: 60, }), detectBot({ mode: "LIVE", allow: [], // "allow none" will block all detected bots }), ],});
export async function POST(event: RequestEvent) { const decision = await aj.protect(event); console.log("Arcjet decision", decision);
for (const result of decision.results) { console.log("Rule Result", result);
if (result.reason.isRateLimit()) { console.log("Rate limit rule", result); }
if (result.reason.isBot()) { console.log("Bot protection rule", result); } }
if (decision.isDenied()) { return error(403, "Forbidden"); }
return json({ message: "Hello world" });}
import { env } from "$env/dynamic/private";import arcjet, { detectBot, fixedWindow } from "@arcjet/sveltekit";import { error, json } from "@sveltejs/kit";
const aj = arcjet({ key: env.ARCJET_KEY, // Get your site key from https://app.arcjet.com rules: [ fixedWindow({ mode: "LIVE", window: "1h", max: 60, }), detectBot({ mode: "LIVE", allow: [], // "allow none" will block all detected bots }), ],});
export async function POST(event) { const decision = await aj.protect(event); console.log("Arcjet decision", decision);
for (const result of decision.results) { console.log("Rule Result", result);
if (result.reason.isRateLimit()) { console.log("Rate limit rule", result); }
if (result.reason.isBot()) { console.log("Bot protection rule", result); } }
if (decision.isDenied()) { return error(403, "Forbidden"); }
return json({ message: "Hello world" });}
This example will log the results of each rule execution.
import arcjet, { fixedWindow, detectBot } from "@arcjet/node";import http from "node:http";
const aj = arcjet({ key: process.env.ARCJET_KEY, // Get your site key from https://app.arcjet.com characteristics: ["ip.src"], rules: [ fixedWindow({ mode: "LIVE", window: "1h", max: 60, }), detectBot({ mode: "LIVE", allow: [], // "allow none" will block all detected bots }), ],});
const server = http.createServer(async function (req, res) { const decision = await aj.protect(req);
for (const result of decision.results) { console.log("Rule Result", result);
if (result.reason.isRateLimit()) { console.log("Rate limit rule", result); }
if (result.reason.isBot()) { console.log("Bot protection rule", result); } }
if (decision.isDenied()) { if (decision.reason.isRateLimit()) { res.writeHead(429, { "Content-Type": "application/json" }); res.end( JSON.stringify({ error: "Too Many Requests", reason: decision.reason }), ); res.end(JSON.stringify({ error: "Forbidden" })); } else { res.writeHead(403, { "Content-Type": "application/json" }); res.end(JSON.stringify({ error: "Forbidden" })); } } else { res.writeHead(200, { "Content-Type": "application/json" }); res.end(JSON.stringify({ message: "Hello world" })); }});
server.listen(8000);
import arcjet, { fixedWindow, detectBot } from "@arcjet/node";import http from "node:http";
const aj = arcjet({ key: process.env.ARCJET_KEY!, // Get your site key from https://app.arcjet.com characteristics: ["ip.src"], rules: [ fixedWindow({ mode: "LIVE", window: "1h", max: 60, }), detectBot({ mode: "LIVE", allow: [], // "allow none" will block all detected bots }), ],});
const server = http.createServer(async function ( req: http.IncomingMessage, res: http.ServerResponse,) { const decision = await aj.protect(req);
for (const result of decision.results) { console.log("Rule Result", result);
if (result.reason.isRateLimit()) { console.log("Rate limit rule", result); }
if (result.reason.isBot()) { console.log("Bot protection rule", result); } }
if (decision.isDenied()) { if (decision.reason.isRateLimit()) { res.writeHead(429, { "Content-Type": "application/json" }); res.end( JSON.stringify({ error: "Too Many Requests", reason: decision.reason }), ); res.end(JSON.stringify({ error: "Forbidden" })); } else { res.writeHead(403, { "Content-Type": "application/json" }); res.end(JSON.stringify({ error: "Forbidden" })); } } else { res.writeHead(200, { "Content-Type": "application/json" }); res.end(JSON.stringify({ message: "Hello world" })); }});
server.listen(8000);
This example will log the results of each rule execution.
import arcjet, { ArcjetRuleResult, detectBot, fixedWindow } from "@arcjet/bun";import { env } from "bun";
const aj = arcjet({ key: env.ARCJET_KEY!, // Get your site key from https://app.arcjet.com rules: [ fixedWindow({ mode: "LIVE", window: "1h", max: 60, }), detectBot({ mode: "LIVE", allow: [], // "allow none" will block all detected bots }), ],});
function isSpoofed(result: ArcjetRuleResult) { return ( // You probably don't want DRY_RUN rules resulting in a denial // since they are generally used for evaluation purposes but you // could log here. result.state !== "DRY_RUN" && result.reason.isBot() && result.reason.isSpoofed() );}
export default { port: 3000, fetch: aj.handler(async (req) => { const decision = await aj.protect(req); console.log("Arcjet decision", decision);
for (const result of decision.results) { console.log("Rule Result", result);
if (result.reason.isRateLimit()) { console.log("Rate limit rule", result); }
if (result.reason.isBot()) { console.log("Bot protection rule", result); } }
// Bots not in the allow list will be blocked if (decision.isDenied()) { return new Response("Forbidden", { status: 403 }); }
// Arcjet Pro plan verifies the authenticity of common bots using IP data. // Verification isn't always possible, so we recommend checking the results // separately. // https://docs.arcjet.com/bot-protection/reference#bot-verification if (decision.results.some(isSpoofed)) { return new Response("Forbidden", { status: 403 }); }
return new Response("Hello world"); }),};
import arcjet, { detectBot, fixedWindow } from "@arcjet/bun";import { env } from "bun";
const aj = arcjet({ key: env.ARCJET_KEY, // Get your site key from https://app.arcjet.com rules: [ fixedWindow({ mode: "LIVE", window: "1h", max: 60, }), detectBot({ mode: "LIVE", allow: [], // "allow none" will block all detected bots }), ],});
function isSpoofed(result) { return ( // You probably don't want DRY_RUN rules resulting in a denial // since they are generally used for evaluation purposes but you // could log here. result.state !== "DRY_RUN" && result.reason.isBot() && result.reason.isSpoofed() );}
export default { port: 3000, fetch: aj.handler(async (req) => { const decision = await aj.protect(req); console.log("Arcjet decision", decision);
for (const result of decision.results) { console.log("Rule Result", result);
if (result.reason.isRateLimit()) { console.log("Rate limit rule", result); }
if (result.reason.isBot()) { console.log("Bot protection rule", result); } }
// Bots not in the allow list will be blocked if (decision.isDenied()) { return new Response("Forbidden", { status: 403 }); }
// Arcjet Pro plan verifies the authenticity of common bots using IP data. // Verification isn't always possible, so we recommend checking the results // separately. // https://docs.arcjet.com/bot-protection/reference#bot-verification if (decision.results.some(isSpoofed)) { return new Response("Forbidden", { status: 403 }); }
return new Response("Hello world"); }),};
This example will log the results of each rule execution. It shows how Arcjet can be integrated into the NestJS logger. See the SDK reference for more details.
import { ARCJET, type ArcjetNest, detectBot, fixedWindow } from "@arcjet/nest";import { Controller, Get, HttpException, HttpStatus, Inject, Injectable, Logger, Req,} from "@nestjs/common";import type { Request } from "express";
// This would normally go in your service file e.g.// src/page/page.service.ts@Injectable()export class PageService { message(): { message: string } { return { message: "Hello world", }; }}
// This would normally go in your controller file e.g.// src/page/page.controller.ts@Controller("page")// Sets up the Arcjet protection without using a guard so we can access the// decision and use it in the controller.export class PageController { // Make use of the NestJS logger: https://docs.nestjs.com/techniques/logger // See // https://github.com/arcjet/example-nestjs/blob/ec742e58c8da52d0a399327182c79e3f4edc8f3b/src/app.module.ts#L29 // and https://github.com/arcjet/example-nestjs/blob/main/src/arcjet-logger.ts // for an example of how to connect Arcjet to the NestJS logger private readonly logger = new Logger(PageController.name);
constructor( private readonly pageService: PageService, @Inject(ARCJET) private readonly arcjet: ArcjetNest, ) {}
@Get() async index(@Req() req: Request) { const decision = await this.arcjet .withRule( detectBot({ mode: "LIVE", // will block requests. Use "DRY_RUN" to log only // configured with a list of bots to allow from // https://arcjet.com/bot-list allow: [], // blocks all automated clients }), ) .withRule( fixedWindow({ mode: "LIVE", window: "1h", max: 60, }), ) .protect(req);
this.logger.log(`Arcjet: id = ${decision.id}`); this.logger.log(`Arcjet: decision = ${decision.conclusion}`);
for (const result of decision.results) { this.logger.log("Rule Result", result);
if (result.reason.isRateLimit()) { this.logger.log("Rate limit rule", result); }
if (result.reason.isBot()) { this.logger.log("Bot protection rule", result); } }
if (decision.isDenied()) { if (decision.reason.isBot()) { throw new HttpException("No bots allowed", HttpStatus.FORBIDDEN); } else { throw new HttpException("Forbidden", HttpStatus.FORBIDDEN); } }
return this.pageService.message(); }}
Identified bots
The decision also contains all of the identified
bots and matched categories detected from the
request. A request may be identified as zero, one, or more bots/categories—all
of which will be available on the decision.allowed
and decision.denied
properties.
import arcjet, { detectBot } from "@arcjet/bun";import { env } from "bun";
const aj = arcjet({ key: env.ARCJET_KEY!, // Get your site key from https://app.arcjet.com rules: [ detectBot({ mode: "LIVE", // will block requests. Use "DRY_RUN" to log only allow: [], // "allow none" will block all detected bots }), ],});
export default { port: 3000, fetch: aj.handler(async (req) => { const decision = await aj.protect(req);
for (const { reason } of decision.results) { if (reason.isBot()) { console.log("detected + allowed bots", reason.allowed); console.log("detected + denied bots", reason.denied);
// Arcjet Pro plan verifies the authenticity of common bots using IP data // https://docs.arcjet.com/bot-protection/reference#bot-verification if (reason.isSpoofed()) { console.log("spoofed bot", reason.spoofed); }
if (reason.isVerified()) { console.log("verified bot", reason.verified); } } }
if (decision.isDenied()) { return new Response("Forbidden", { status: 403 }); }
return new Response("Hello world"); }),};
import arcjet, { detectBot } from "@arcjet/bun";import { env } from "bun";
const aj = arcjet({ key: env.ARCJET_KEY, // Get your site key from https://app.arcjet.com rules: [ detectBot({ mode: "LIVE", // will block requests. Use "DRY_RUN" to log only allow: [], // "allow none" will block all detected bots }), ],});
export default { port: 3000, fetch: aj.handler(async (req) => { const decision = await aj.protect(req);
for (const { reason } of decision.results) { if (reason.isBot()) { console.log("detected + allowed bots", reason.allowed); console.log("detected + denied bots", reason.denied);
// Arcjet Pro plan verifies the authenticity of common bots using IP data // https://docs.arcjet.com/bot-protection/reference#bot-verification if (reason.isSpoofed()) { console.log("spoofed bot", reason.spoofed); }
if (reason.isVerified()) { console.log("verified bot", reason.verified); } } }
if (decision.isDenied()) { return new Response("Forbidden", { status: 403 }); }
return new Response("Hello world"); }),};
import arcjet, { detectBot } from "@arcjet/deno";
const aj = arcjet({ key: Deno.env.get("ARCJET_KEY")!, // Get your site key from https://app.arcjet.com rules: [ detectBot({ mode: "LIVE", // will block requests. Use "DRY_RUN" to log only allow: [], // "allow none" will block all detected bots }), ],});
Deno.serve( { port: 3000 }, aj.handler(async (req) => { const decision = await aj.protect(req);
for (const { reason } of decision.results) { if (reason.isBot()) { console.log("detected + allowed bots", reason.allowed); console.log("detected + denied bots", reason.denied);
// Arcjet Pro plan verifies the authenticity of common bots using IP data // https://docs.arcjet.com/bot-protection/reference#bot-verification if (reason.isSpoofed()) { console.log("spoofed bot", reason.spoofed); }
if (reason.isVerified()) { console.log("verified bot", reason.verified); } } }
if (decision.isDenied()) { return new Response("Forbidden", { status: 403 }); }
return new Response("Hello world"); }),);
import arcjet, { detectBot } from "@arcjet/next";import { NextResponse } from "next/server";
const aj = arcjet({ key: process.env.ARCJET_KEY!, rules: [ detectBot({ mode: "LIVE", allow: [], // "allow none" will block all detected bots }), ],});
export async function POST(req: Request) { const decision = await aj.protect(req);
for (const { reason } of decision.results) { if (reason.isBot()) { console.log("detected + allowed bots", reason.allowed); console.log("detected + denied bots", reason.denied);
// Arcjet Pro plan verifies the authenticity of common bots using IP data // https://docs.arcjet.com/bot-protection/reference#bot-verification if (reason.isSpoofed()) { console.log("spoofed bot", reason.spoofed); }
if (reason.isVerified()) { console.log("verified bot", reason.verified); } } }
if (decision.isDenied()) { return NextResponse.json({ error: "You are a bot!" }, { status: 403 }); }
return NextResponse.json({ message: "Hello world", });}
import arcjet, { detectBot } from "@arcjet/next";
const aj = arcjet({ key: process.env.ARCJET_KEY, rules: [ detectBot({ mode: "LIVE", allow: [], // "allow none" will block all detected bots }), ],});
export default async function handler(req, res) { const decision = await aj.protect(req);
for (const { reason } of decision.results) { if (reason.isBot()) { console.log("detected + allowed bots", reason.allowed); console.log("detected + denied bots", reason.denied);
// Arcjet Pro plan verifies the authenticity of common bots using IP data // https://docs.arcjet.com/bot-protection/reference#bot-verification if (reason.isSpoofed()) { console.log("spoofed bot", reason.spoofed); }
if (reason.isVerified()) { console.log("verified bot", reason.verified); } } }
if (decision.isDenied()) { return res.status(403).json({ error: "Forbidden" }); }
res.status(200).json({ name: "Hello world" });}
import arcjet, { detectBot } from "@arcjet/next";import type { NextApiRequest, NextApiResponse } from "next";
const aj = arcjet({ key: process.env.ARCJET_KEY!, rules: [ detectBot({ mode: "LIVE", allow: [], // "allow none" will block all detected bots }), ],});
export default async function handler( req: NextApiRequest, res: NextApiResponse,) { const decision = await aj.protect(req);
for (const { reason } of decision.results) { if (reason.isBot()) { console.log("detected + allowed bots", reason.allowed); console.log("detected + denied bots", reason.denied);
// Arcjet Pro plan verifies the authenticity of common bots using IP data // https://docs.arcjet.com/bot-protection/reference#bot-verification if (reason.isSpoofed()) { console.log("spoofed bot", reason.spoofed); }
if (reason.isVerified()) { console.log("verified bot", reason.verified); } } }
if (decision.isDenied()) { return res.status(403).json({ error: "Forbidden" }); }
res.status(200).json({ name: "Hello world" });}
import arcjet, { detectBot } from "@arcjet/next";import { NextResponse } from "next/server";
const aj = arcjet({ key: process.env.ARCJET_KEY, rules: [ detectBot({ mode: "LIVE", allow: [], // "allow none" will block all detected bots }), ],});
export async function POST(req) { const decision = await aj.protect(req);
for (const { reason } of decision.results) { if (reason.isBot()) { console.log("detected + allowed bots", reason.allowed); console.log("detected + denied bots", reason.denied);
// Arcjet Pro plan verifies the authenticity of common bots using IP data // https://docs.arcjet.com/bot-protection/reference#bot-verification if (reason.isSpoofed()) { console.log("spoofed bot", reason.spoofed); }
if (reason.isVerified()) { console.log("verified bot", reason.verified); } } }
if (decision.isDenied()) { return NextResponse.json({ error: "You are a bot!" }, { status: 403 }); }
return NextResponse.json({ message: "Hello world", });}
import arcjet, { detectBot } from "@arcjet/remix";import type { LoaderFunctionArgs } from "@remix-run/node";
const aj = arcjet({ key: process.env.ARCJET_KEY!, rules: [ detectBot({ mode: "LIVE", // will block requests. Use "DRY_RUN" to log only allow: [], // "allow none" will block all detected bots }), ],});
export async function loader(args: LoaderFunctionArgs) { const decision = await aj.protect(args);
for (const { reason } of decision.results) { if (reason.isBot()) { console.log("detected + allowed bots", reason.allowed); console.log("detected + denied bots", reason.denied);
// Arcjet Pro plan verifies the authenticity of common bots using IP data // https://docs.arcjet.com/bot-protection/reference#bot-verification if (reason.isSpoofed()) { console.log("spoofed bot", reason.spoofed); }
if (reason.isVerified()) { console.log("verified bot", reason.verified); } } }
if (decision.isDenied()) { throw new Response("Forbidden", { status: 403, statusText: "Forbidden" }); }
return null;}
import arcjet, { detectBot } from "@arcjet/remix";
const aj = arcjet({ key: process.env.ARCJET_KEY, rules: [ detectBot({ mode: "LIVE", // will block requests. Use "DRY_RUN" to log only allow: [], // "allow none" will block all detected bots }), ],});
export async function loader(args) { const decision = await aj.protect(args);
for (const { reason } of decision.results) { if (reason.isBot()) { console.log("detected + allowed bots", reason.allowed); console.log("detected + denied bots", reason.denied);
// Arcjet Pro plan verifies the authenticity of common bots using IP data // https://docs.arcjet.com/bot-protection/reference#bot-verification if (reason.isSpoofed()) { console.log("spoofed bot", reason.spoofed); }
if (reason.isVerified()) { console.log("verified bot", reason.verified); } } }
if (decision.isDenied()) { throw new Response("Forbidden", { status: 403, statusText: "Forbidden" }); }
return null;}
import arcjet, { detectBot } from "@arcjet/node";import http from "node:http";
const aj = arcjet({ key: process.env.ARCJET_KEY, // Get your site key from https://app.arcjet.com rules: [ detectBot({ mode: "LIVE", // will block requests. Use "DRY_RUN" to log only allow: [], // "allow none" will block all detected bots }), ],});
const server = http.createServer(async function (req, res) { const decision = await aj.protect(req);
for (const { reason } of decision.results) { if (reason.isBot()) { console.log("detected + allowed bots", reason.allowed); console.log("detected + denied bots", reason.denied);
// Arcjet Pro plan verifies the authenticity of common bots using IP data // https://docs.arcjet.com/bot-protection/reference#bot-verification if (reason.isSpoofed()) { console.log("spoofed bot", reason.spoofed); }
if (reason.isVerified()) { console.log("verified bot", reason.verified); } } }
if (decision.isDenied()) { res.writeHead(403, { "Content-Type": "application/json" }); res.end(JSON.stringify({ error: "Forbidden" })); } else { res.writeHead(200, { "Content-Type": "application/json" }); res.end(JSON.stringify({ message: "Hello world" })); }});
server.listen(8000);
import arcjet, { detectBot } from "@arcjet/node";import http from "node:http";
const aj = arcjet({ key: process.env.ARCJET_KEY!, // Get your site key from https://app.arcjet.com rules: [ detectBot({ mode: "LIVE", // will block requests. Use "DRY_RUN" to log only allow: [], // "allow none" will block all detected bots }), ],});
const server = http.createServer(async function ( req: http.IncomingMessage, res: http.ServerResponse,) { const decision = await aj.protect(req);
for (const { reason } of decision.results) { if (reason.isBot()) { console.log("detected + allowed bots", reason.allowed); console.log("detected + denied bots", reason.denied);
// Arcjet Pro plan verifies the authenticity of common bots using IP data // https://docs.arcjet.com/bot-protection/reference#bot-verification if (reason.isSpoofed()) { console.log("spoofed bot", reason.spoofed); }
if (reason.isVerified()) { console.log("verified bot", reason.verified); } } }
if (decision.isDenied()) { res.writeHead(403, { "Content-Type": "application/json" }); res.end(JSON.stringify({ error: "Forbidden" })); } else { res.writeHead(200, { "Content-Type": "application/json" }); res.end(JSON.stringify({ message: "Hello world" })); }});
server.listen(8000);
import { env } from "$env/dynamic/private";import arcjet, { detectBot } from "@arcjet/sveltekit";import { error } from "@sveltejs/kit";
const aj = arcjet({ key: env.ARCJET_KEY, // Get your site key from https://app.arcjet.com rules: [ detectBot({ mode: "LIVE", allow: [], // "allow none" will block all detected bots }), ],});
export async function handle({ event, resolve }) { const decision = await aj.protect(event);
for (const { reason } of decision.results) { if (reason.isBot()) { console.log("detected + allowed bots", reason.allowed); console.log("detected + denied bots", reason.denied);
// Arcjet Pro plan verifies the authenticity of common bots using IP data // https://docs.arcjet.com/bot-protection/reference#bot-verification if (reason.isSpoofed()) { console.log("spoofed bot", reason.spoofed); }
if (reason.isVerified()) { console.log("verified bot", reason.verified); } } }
if (decision.isDenied()) { return error(403, "You are a bot!"); }
return resolve(event);}
import { env } from "$env/dynamic/private";import arcjet, { detectBot } from "@arcjet/sveltekit";import { error, type RequestEvent } from "@sveltejs/kit";
const aj = arcjet({ key: env.ARCJET_KEY!, // Get your site key from https://app.arcjet.com rules: [ detectBot({ mode: "LIVE", allow: [], // "allow none" will block all detected bots }), ],});
export async function handle({ event, resolve,}: { event: RequestEvent; resolve: (event: RequestEvent) => Response | Promise<Response>;}): Promise<Response> { const decision = await aj.protect(event);
for (const { reason } of decision.results) { if (reason.isBot()) { console.log("detected + allowed bots", reason.allowed); console.log("detected + denied bots", reason.denied);
// Arcjet Pro plan verifies the authenticity of common bots using IP data // https://docs.arcjet.com/bot-protection/reference#bot-verification if (reason.isSpoofed()) { console.log("spoofed bot", reason.spoofed); }
if (reason.isVerified()) { console.log("verified bot", reason.verified); } } }
if (decision.isDenied()) { return error(403, "You are a bot!"); }
return resolve(event);}
import { ARCJET, type ArcjetNest, detectBot } from "@arcjet/nest";import { Controller, Get, HttpException, HttpStatus, Inject, Injectable, Logger, Req,} from "@nestjs/common";import type { Request } from "express";
// This would normally go in your service file e.g.// src/page/page.service.ts@Injectable()export class PageService { message(): { message: string } { return { message: "Hello world", }; }}
// This would normally go in your controller file e.g.// src/page/page.controller.ts@Controller("page")// Sets up the Arcjet protection without using a guard so we can access the// decision and use it in the controller.export class PageController { // Make use of the NestJS logger: https://docs.nestjs.com/techniques/logger // See // https://github.com/arcjet/example-nestjs/blob/ec742e58c8da52d0a399327182c79e3f4edc8f3b/src/app.module.ts#L29 // and https://github.com/arcjet/example-nestjs/blob/main/src/arcjet-logger.ts // for an example of how to connect Arcjet to the NestJS logger private readonly logger = new Logger(PageController.name);
constructor( private readonly pageService: PageService, @Inject(ARCJET) private readonly arcjet: ArcjetNest, ) {}
@Get() async index(@Req() req: Request) { const decision = await this.arcjet .withRule( detectBot({ mode: "LIVE", // will block requests. Use "DRY_RUN" to log only // configured with a list of bots to allow from // https://arcjet.com/bot-list allow: [], // blocks all automated clients }), ) .protect(req);
for (const { reason } of decision.results) { if (reason.isBot()) { this.logger.log("detected + allowed bots", reason.allowed); this.logger.log("detected + denied bots", reason.denied);
// Arcjet Pro plan verifies the authenticity of common bots using IP data // https://docs.arcjet.com/bot-protection/reference#bot-verification if (reason.isSpoofed()) { this.logger.log("spoofed bot", reason.spoofed); }
if (reason.isVerified()) { this.logger.log("verified bot", reason.verified); } } }
if (decision.isDenied()) { if (decision.reason.isBot()) { throw new HttpException("No bots allowed", HttpStatus.FORBIDDEN); } else { throw new HttpException("Forbidden", HttpStatus.FORBIDDEN); } }
return this.pageService.message(); }}
Error handling
Arcjet is designed to fail open so that a service issue or misconfiguration does
not block all requests. The SDK will also time out and fail open after 1000ms
when NODE_ENV
or ARCJET_ENV
is development
and 500ms otherwise. However,
in most cases, the response time will be less than 20-30ms.
If there is an error condition when processing the rule, Arcjet will return an
ERROR
result for that rule and you can check the message
property on the rule’s
error result for more information.
If all other rules that were run returned an ALLOW
result, then the final Arcjet
conclusion will be ERROR
.
import arcjet, { detectBot } from "@arcjet/deno";
const aj = arcjet({ key: Deno.env.get("ARCJET_KEY")!, // Get your site key from https://app.arcjet.com rules: [ detectBot({ mode: "LIVE", allow: [], // "allow none" will block all detected bots }), ],});
Deno.serve( { port: 3000 }, aj.handler(async (req) => { const decision = await aj.protect(req);
for (const { reason, state } of decision.results) { if (reason.isError()) { if (reason.message.includes("requires user-agent header")) { // Requests without User-Agent headers can not be identified as any // particular bot and will be marked as an errored rule. Most // legitimate clients always send this header, so we recommend blocking // requests without it. // See https://docs.arcjet.com/bot-protection/concepts#user-agent-header console.warn("User-Agent header is missing");
if (state !== "DRY_RUN") { return new Response("Bad request", { status: 400 }); } } else { // Fail open by logging the error and continuing console.warn("Arcjet error", reason.message); // You could also fail closed here for very sensitive routes //return new Response("Service unavailable", { status: 503 }); } } }
if (decision.isDenied()) { return new Response("Forbidden", { status: 403 }); }
return new Response("Hello world"); }),);
import arcjet, { detectBot } from "@arcjet/remix";import type { LoaderFunctionArgs } from "@remix-run/node";
const aj = arcjet({ key: process.env.ARCJET_KEY!, rules: [ detectBot({ mode: "LIVE", allow: [], // "allow none" will block all detected bots }), ],});
export async function loader(args: LoaderFunctionArgs) { const decision = await aj.protect(args);
for (const { reason, state } of decision.results) { if (reason.isError()) { if (reason.message.includes("requires user-agent header")) { // Requests without User-Agent headers can not be identified as any // particular bot and will be marked as an errored rule. Most // legitimate clients always send this header, so we recommend blocking // requests without it. // See https://docs.arcjet.com/bot-protection/concepts#user-agent-header console.warn("User-Agent header is missing");
if (state !== "DRY_RUN") { throw new Response("Bad request", { status: 400 }); } } else { // Fail open by logging the error and continuing console.warn("Arcjet error", reason.message); // You could also fail closed here for very sensitive routes //throw new Response("Service unavailable", { status: 503 }); } } }
if (decision.isDenied()) { throw new Response("Forbidden", { status: 403, statusText: "Forbidden" }); }
return null;}
import arcjet, { detectBot } from "@arcjet/remix";
const aj = arcjet({ key: process.env.ARCJET_KEY, rules: [ detectBot({ mode: "LIVE", allow: [], // "allow none" will block all detected bots }), ],});
export async function loader(args) { const decision = await aj.protect(args);
for (const { reason, state } of decision.results) { if (reason.isError()) { if (reason.message.includes("requires user-agent header")) { // Requests without User-Agent headers can not be identified as any // particular bot and will be marked as an errored rule. Most // legitimate clients always send this header, so we recommend blocking // requests without it. // See https://docs.arcjet.com/bot-protection/concepts#user-agent-header console.warn("User-Agent header is missing");
if (state !== "DRY_RUN") { throw new Response("Bad request", { status: 400 }); } } else { // Fail open by logging the error and continuing console.warn("Arcjet error", reason.message); // You could also fail closed here for very sensitive routes //throw new Response("Service unavailable", { status: 503 }); } } }
if (decision.isDenied()) { throw new Response("Forbidden", { status: 403, statusText: "Forbidden" }); }
return null;}
import { env } from "$env/dynamic/private";import arcjet, { detectBot } from "@arcjet/sveltekit";import { error, json, type RequestEvent } from "@sveltejs/kit";
const aj = arcjet({ key: env.ARCJET_KEY!, rules: [ detectBot({ mode: "LIVE", allow: [], // "allow none" will block all detected bots }), ],});
export async function GET(event: RequestEvent) { const decision = await aj.protect(event);
for (const { reason, state } of decision.results) { if (reason.isError()) { if (reason.message.includes("requires user-agent header")) { // Requests without User-Agent headers can not be identified as any // particular bot and will be marked as an errored rule. Most // legitimate clients always send this header, so we recommend blocking // requests without it. // See https://docs.arcjet.com/bot-protection/concepts#user-agent-header console.warn("User-Agent header is missing");
if (state !== "DRY_RUN") { return error(400, { message: "Bad request" }); } } else { // Fail open by logging the error and continuing console.warn("Arcjet error", reason.message); // You could also fail closed here for very sensitive routes //return error(503, { message: "Service unavailable" }); } } }
if (decision.isDenied()) { return error(403, { message: "You are a bot!" }); }
return json({ message: "Hello world" });}
import { env } from "$env/dynamic/private";import arcjet, { detectBot } from "@arcjet/sveltekit";import { error, json } from "@sveltejs/kit";
const aj = arcjet({ key: env.ARCJET_KEY, rules: [ detectBot({ mode: "LIVE", allow: [], // "allow none" will block all detected bots }), ],});
export async function GET(event) { const decision = await aj.protect(event);
for (const { reason, state } of decision.results) { if (reason.isError()) { if (reason.message.includes("requires user-agent header")) { // Requests without User-Agent headers can not be identified as any // particular bot and will be marked as an errored rule. Most // legitimate clients always send this header, so we recommend blocking // requests without it. // See https://docs.arcjet.com/bot-protection/concepts#user-agent-header console.warn("User-Agent header is missing");
if (state !== "DRY_RUN") { return error(400, { message: "Bad request" }); } } else { // Fail open by logging the error and continuing console.warn("Arcjet error", reason.message); // You could also fail closed here for very sensitive routes //return error(503, { message: "Service unavailable" }); } } }
if (decision.isDenied()) { return error(403, { message: "You are a bot!" }); }
return json({ message: "Hello world" });}
import arcjet, { detectBot } from "@arcjet/node";import http from "node:http";
const aj = arcjet({ key: process.env.ARCJET_KEY, // Get your site key from https://app.arcjet.com rules: [ detectBot({ mode: "LIVE", // will block requests. Use "DRY_RUN" to log only allow: [], // "allow none" will block all detected bots }), ],});
const server = http.createServer(async function (req, res) { const decision = await aj.protect(req);
for (const { reason, state } of decision.results) { if (reason.isError()) { if (reason.message.includes("requires user-agent header")) { // Requests without User-Agent headers can not be identified as any // particular bot and will be marked as an errored rule. Most // legitimate clients always send this header, so we recommend blocking // requests without it. // See https://docs.arcjet.com/bot-protection/concepts#user-agent-header console.warn("User-Agent header is missing");
if (state !== "DRY_RUN") { res.writeHead(400, { "Content-Type": "application/json" }); res.end(JSON.stringify({ error: "Bad request" })); return; } } else { // Fail open by logging the error and continuing console.warn("Arcjet error", reason.message); // You could also fail closed here for very sensitive routes //res.writeHead(503, { "Content-Type": "application/json" }); //res.end(JSON.stringify({ error: "Service unavailable" })); } } }
if (decision.isDenied()) { res.writeHead(403, { "Content-Type": "application/json" }); res.end(JSON.stringify({ error: "Forbidden" })); } else { res.writeHead(200, { "Content-Type": "application/json" }); res.end(JSON.stringify({ message: "Hello world" })); }});
server.listen(8000);
import arcjet, { detectBot } from "@arcjet/node";import http from "node:http";
const aj = arcjet({ key: process.env.ARCJET_KEY!, // Get your site key from https://app.arcjet.com rules: [ detectBot({ mode: "LIVE", // will block requests. Use "DRY_RUN" to log only allow: [], // "allow none" will block all detected bots }), ],});
const server = http.createServer(async function ( req: http.IncomingMessage, res: http.ServerResponse,) { const decision = await aj.protect(req);
for (const { reason, state } of decision.results) { if (reason.isError()) { if (reason.message.includes("requires user-agent header")) { // Requests without User-Agent headers can not be identified as any // particular bot and will be marked as an errored rule. Most // legitimate clients always send this header, so we recommend blocking // requests without it. // See https://docs.arcjet.com/bot-protection/concepts#user-agent-header console.warn("User-Agent header is missing");
if (state !== "DRY_RUN") { res.writeHead(400, { "Content-Type": "application/json" }); res.end(JSON.stringify({ error: "Bad request" })); return; } } else { // Fail open by logging the error and continuing console.warn("Arcjet error", reason.message); // You could also fail closed here for very sensitive routes //res.writeHead(503, { "Content-Type": "application/json" }); //res.end(JSON.stringify({ error: "Service unavailable" })); } } }
if (decision.isDenied()) { res.writeHead(403, { "Content-Type": "application/json" }); res.end(JSON.stringify({ error: "Forbidden" })); } else { res.writeHead(200, { "Content-Type": "application/json" }); res.end(JSON.stringify({ message: "Hello world" })); }});
server.listen(8000);
import arcjet, { detectBot } from "@arcjet/next";
const aj = arcjet({ key: process.env.ARCJET_KEY, rules: [ detectBot({ mode: "LIVE", allow: [], // "allow none" will block all detected bots }), ],});
export default async function handler(req, res) { const decision = await aj.protect(req);
for (const { reason, state } of decision.results) { if (reason.isError()) { if (reason.message.includes("requires user-agent header")) { // Requests without User-Agent headers can not be identified as any // particular bot and will be marked as an errored decision. Most // legitimate clients always send this header, so we recommend blocking // requests without it. // See https://docs.arcjet.com/bot-protection/concepts#user-agent-header console.warn("User-Agent header is missing");
if (state !== "DRY_RUN") { return res.status(400).json({ error: "Bad request" }); } } else { // Fail open by logging the error and continuing console.warn("Arcjet error", reason.message); // You could also fail closed here for very sensitive routes //return res.status(503).json({ error: "Service unavailable" }); } } }
if (decision.isDenied()) { return res.status(403).json({ error: "You are a bot!", }); }
res.status(200).json({ name: "Hello world" });}
import arcjet, { detectBot } from "@arcjet/next";import type { NextApiRequest, NextApiResponse } from "next";
const aj = arcjet({ key: process.env.ARCJET_KEY!, rules: [ detectBot({ mode: "LIVE", allow: [], // "allow none" will block all detected bots }), ],});
export default async function handler( req: NextApiRequest, res: NextApiResponse,) { const decision = await aj.protect(req);
for (const { reason, state } of decision.results) { if (reason.isError()) { if (reason.message.includes("requires user-agent header")) { // Requests without User-Agent headers can not be identified as any // particular bot and will be marked as an errored decision. Most // legitimate clients always send this header, so we recommend blocking // requests without it. // See https://docs.arcjet.com/bot-protection/concepts#user-agent-header console.warn("User-Agent header is missing");
if (state !== "DRY_RUN") { return res.status(400).json({ error: "Bad request" }); } } else { // Fail open by logging the error and continuing console.warn("Arcjet error", reason.message); // You could also fail closed here for very sensitive routes //return res.status(503).json({ error: "Service unavailable" }); } } }
if (decision.isDenied()) { return res.status(403).json({ error: "You are a bot!", }); }
res.status(200).json({ name: "Hello world" });}
import arcjet, { detectBot } from "@arcjet/next";import { NextResponse } from "next/server";
const aj = arcjet({ key: process.env.ARCJET_KEY!, rules: [ detectBot({ mode: "LIVE", allow: [], // "allow none" will block all detected bots }), ],});
export async function GET(req: Request) { const decision = await aj.protect(req);
for (const { reason, state } of decision.results) { if (reason.isError()) { if (reason.message.includes("requires user-agent header")) { // Requests without User-Agent headers can not be identified as any // particular bot and will be marked as an errored decision. Most // legitimate clients always send this header, so we recommend blocking // requests without it. // See https://docs.arcjet.com/bot-protection/concepts#user-agent-header console.warn("User-Agent header is missing");
if (state !== "DRY_RUN") { return NextResponse.json( { error: "Bad request", }, { status: 400 }, ); } } else { // Fail open by logging the error and continuing console.warn("Arcjet error", reason.message); // You could also fail closed here for very sensitive routes // return NextResponse.json( // { // error: "Service unavailable", // }, // { status: 503 }, // ); } } }
if (decision.isDenied()) { return NextResponse.json( { error: "You are a bot!", }, { status: 403, }, ); }
return NextResponse.json({ message: "Hello world", });}
import arcjet, { detectBot } from "@arcjet/next";import { NextResponse } from "next/server";
const aj = arcjet({ key: process.env.ARCJET_KEY, rules: [ detectBot({ mode: "LIVE", allow: [], // "allow none" will block all detected bots }), ],});
export async function GET(req) { const decision = await aj.protect(req);
for (const { reason, state } of decision.results) { if (reason.isError()) { if (reason.message.includes("requires user-agent header")) { // Requests without User-Agent headers can not be identified as any // particular bot and will be marked as an errored decision. Most // legitimate clients always send this header, so we recommend blocking // requests without it. // See https://docs.arcjet.com/bot-protection/concepts#user-agent-header console.warn("User-Agent header is missing");
if (state !== "DRY_RUN") { return NextResponse.json( { error: "Bad request", }, { status: 400 }, ); } } else { // Fail open by logging the error and continuing console.warn("Arcjet error", reason.message); // You could also fail closed here for very sensitive routes // return NextResponse.json( // { // error: "Service unavailable", // }, // { status: 503 }, // ); } } }
if (decision.isDenied()) { return NextResponse.json( { error: "You are a bot!", }, { status: 403 }, ); }
return NextResponse.json({ message: "Hello world", });}
import arcjet, { ArcjetRuleResult, detectBot } from "@arcjet/bun";import { env } from "bun";
const aj = arcjet({ key: env.ARCJET_KEY!, // Get your site key from https://app.arcjet.com rules: [ detectBot({ mode: "LIVE", allow: [], // "allow none" will block all detected bots }), ],});
function isSpoofed(result: ArcjetRuleResult) { return ( // You probably don't want DRY_RUN rules resulting in a denial // since they are generally used for evaluation purposes but you // could log here. result.state !== "DRY_RUN" && result.reason.isBot() && result.reason.isSpoofed() );}
export default { port: 3000, fetch: aj.handler(async (req) => { const decision = await aj.protect(req);
for (const { reason, state } of decision.results) { if (reason.isError()) { if (reason.message.includes("requires user-agent header")) { // Requests without User-Agent headers can not be identified as any // particular bot and will be marked as an errored decision. Most // legitimate clients always send this header, so we recommend blocking // requests without it. // See https://docs.arcjet.com/bot-protection/concepts#user-agent-header console.warn("User-Agent header is missing");
if (state !== "DRY_RUN") { return new Response("Bad request", { status: 400 }); } } else { // Fail open by logging the error and continuing console.warn("Arcjet error", reason.message); // You could also fail closed here for very sensitive routes //return new Response("Service unavailable", { status: 503 }); } } }
// Bots not in the allow list will be blocked if (decision.isDenied()) { return new Response("Forbidden", { status: 403 }); }
// Arcjet Pro plan verifies the authenticity of common bots using IP data. // Verification isn't always possible, so we recommend checking the results // separately. // https://docs.arcjet.com/bot-protection/reference#bot-verification if (decision.results.some(isSpoofed)) { return new Response("Forbidden", { status: 403 }); }
return new Response("Hello world"); }),};
import arcjet, { detectBot } from "@arcjet/bun";import { env } from "bun";
const aj = arcjet({ key: env.ARCJET_KEY, // Get your site key from https://app.arcjet.com rules: [ detectBot({ mode: "LIVE", allow: [], // "allow none" will block all detected bots }), ],});
function isSpoofed(result) { return ( // You probably don't want DRY_RUN rules resulting in a denial // since they are generally used for evaluation purposes but you // could log here. result.state !== "DRY_RUN" && result.reason.isBot() && result.reason.isSpoofed() );}
export default { port: 3000, fetch: aj.handler(async (req) => { const decision = await aj.protect(req);
for (const { reason, state } of decision.results) { if (reason.isError()) { if (reason.message.includes("requires user-agent header")) { // Requests without User-Agent headers can not be identified as any // particular bot and will be marked as an errored decision. Most // legitimate clients always send this header, so we recommend blocking // requests without it. // See https://docs.arcjet.com/bot-protection/concepts#user-agent-header console.warn("User-Agent header is missing");
if (state !== "DRY_RUN") { return new Response("Bad request", { status: 400 }); } } else { // Fail open by logging the error and continuing console.warn("Arcjet error", reason.message); // You could also fail closed here for very sensitive routes //return new Response("Service unavailable", { status: 503 }); } } }
// Bots not in the allow list will be blocked if (decision.isDenied()) { return new Response("Forbidden", { status: 403 }); }
// Arcjet Pro plan verifies the authenticity of common bots using IP data. // Verification isn't always possible, so we recommend checking the results // separately. // https://docs.arcjet.com/bot-protection/reference#bot-verification if (decision.results.some(isSpoofed)) { return new Response("Forbidden", { status: 403 }); }
return new Response("Hello world"); }),};
import { ARCJET, type ArcjetNest, detectBot } from "@arcjet/nest";import { Controller, Get, HttpException, HttpStatus, Inject, Injectable, Logger, Req,} from "@nestjs/common";import type { Request } from "express";
// This would normally go in your service file e.g.// src/page/page.service.ts@Injectable()export class PageService { message(): { message: string } { return { message: "Hello world", }; }}
// This would normally go in your controller file e.g.// src/page/page.controller.ts@Controller("page")// Sets up the Arcjet protection without using a guard so we can access the// decision and use it in the controller.export class PageController { // Make use of the NestJS logger: https://docs.nestjs.com/techniques/logger // See // https://github.com/arcjet/example-nestjs/blob/ec742e58c8da52d0a399327182c79e3f4edc8f3b/src/app.module.ts#L29 // and https://github.com/arcjet/example-nestjs/blob/main/src/arcjet-logger.ts // for an example of how to connect Arcjet to the NestJS logger private readonly logger = new Logger(PageController.name);
constructor( private readonly pageService: PageService, @Inject(ARCJET) private readonly arcjet: ArcjetNest, ) {}
@Get() async index(@Req() req: Request) { const decision = await this.arcjet .withRule( detectBot({ mode: "LIVE", // will block requests. Use "DRY_RUN" to log only // configured with a list of bots to allow from // https://arcjet.com/bot-list allow: [], // blocks all automated clients }), ) .protect(req);
for (const { reason, state } of decision.results) { if (reason.isError()) { if (reason.message.includes("requires user-agent header")) { // Requests without User-Agent headers can not be identified as any // particular bot and will be marked as an errored rule. Most // legitimate clients always send this header, so we recommend blocking // requests without it. // See https://docs.arcjet.com/bot-protection/concepts#user-agent-header this.logger.warn("User-Agent header is missing");
if (state !== "DRY_RUN") { throw new HttpException("Bad request", HttpStatus.BAD_REQUEST); } } else { // Fail open by logging the error and continuing this.logger.error(`Arcjet error: ${reason.message}`); // You could also fail closed here for very sensitive routes //throw new HttpException("Service unavailable", HttpStatus.SERVICE_UNAVAILABLE); } } }
if (decision.isDenied()) { if (decision.reason.isBot()) { throw new HttpException("No bots allowed", HttpStatus.FORBIDDEN); } else { throw new HttpException("Forbidden", HttpStatus.FORBIDDEN); } }
return this.pageService.message(); }}
Filtering categories
All categories are also provided as enumerations, which allows for programmatic
access. For example, you may want to allow most of CATEGORY:GOOGLE
except
their “advertising quality” bot.
import { botCategories, detectBot } from "@arcjet/nest";// ...// This is part of the rules constructed using withRule or a guard// ...detectBot({ mode: "LIVE", // configured with a list of bots to allow from // https://arcjet.com/bot-list - all other detected bots will be blocked allow: [ // filter a category to remove individual bots from our provided lists ...botCategories["CATEGORY:GOOGLE"].filter( (bot) => bot !== "GOOGLE_ADSBOT" && bot !== "GOOGLE_ADSBOT_MOBILE", ), ],});
import arcjet, { botCategories, detectBot } from "@arcjet/node";
const aj = arcjet({ key: process.env.ARCJET_KEY!, rules: [ detectBot({ mode: "LIVE", // configured with a list of bots to allow from // https://arcjet.com/bot-list - all other detected bots will be blocked allow: [ // filter a category to remove individual bots from our provided lists ...botCategories["CATEGORY:GOOGLE"].filter( (bot) => bot !== "GOOGLE_ADSBOT" && bot !== "GOOGLE_ADSBOT_MOBILE", ), ], }), ],});
import arcjet, { botCategories, detectBot } from "@arcjet/node";
const aj = arcjet({ key: process.env.ARCJET_KEY, rules: [ detectBot({ mode: "LIVE", // configured with a list of bots to allow from // https://arcjet.com/bot-list - all other detected bots will be blocked allow: [ // filter a category to remove individual bots from our provided lists ...botCategories["CATEGORY:GOOGLE"].filter( (bot) => bot !== "GOOGLE_ADSBOT" && bot !== "GOOGLE_ADSBOT_MOBILE", ), ], }), ],});
import arcjet, { botCategories, detectBot } from "@arcjet/bun";import { env } from "bun";
const aj = arcjet({ key: env.ARCJET_KEY!, // Get your site key from https://app.arcjet.com rules: [ detectBot({ mode: "LIVE", // configured with a list of bots to allow from // https://arcjet.com/bot-list - all other detected bots will be blocked allow: [ // filter a category to remove individual bots from our provided lists ...botCategories["CATEGORY:GOOGLE"].filter( (bot) => bot !== "GOOGLE_ADSBOT" && bot !== "GOOGLE_ADSBOT_MOBILE", ), ], }), ],});
export default { port: 3000, fetch: aj.handler(async (req) => { const decision = await aj.protect(req);
// Bots not in the allow list will be blocked if (decision.isDenied()) { return new Response("Forbidden", { status: 403 }); }
return new Response("Hello world"); }),};
import arcjet, { botCategories, detectBot } from "@arcjet/bun";import { env } from "bun";
const aj = arcjet({ key: env.ARCJET_KEY, // Get your site key from https://app.arcjet.com rules: [ detectBot({ mode: "LIVE", // configured with a list of bots to allow from // https://arcjet.com/bot-list - all other detected bots will be blocked allow: [ // filter a category to remove individual bots from our provided lists ...botCategories["CATEGORY:GOOGLE"].filter( (bot) => bot !== "GOOGLE_ADSBOT" && bot !== "GOOGLE_ADSBOT_MOBILE", ), ], }), ],});
export default { port: 3000, fetch: aj.handler(async (req) => { const decision = await aj.protect(req);
// Bots not in the allow list will be blocked if (decision.isDenied()) { return new Response("Forbidden", { status: 403 }); }
return new Response("Hello world"); }),};
import arcjet, { botCategories, detectBot } from "@arcjet/deno";
const aj = arcjet({ key: Deno.env.get("ARCJET_KEY")!, // Get your site key from https://app.arcjet.com rules: [ detectBot({ mode: "LIVE", // configured with a list of bots to allow from // https://arcjet.com/bot-list - all other detected bots will be blocked allow: [ // filter a category to remove individual bots from our provided lists ...botCategories["CATEGORY:GOOGLE"].filter( (bot) => bot !== "GOOGLE_ADSBOT" && bot !== "GOOGLE_ADSBOT_MOBILE", ), ], }), ],});
Deno.serve( { port: 3000 }, aj.handler(async (req) => { const decision = await aj.protect(req);
// Bots not in the allow list will be blocked if (decision.isDenied()) { return new Response("Forbidden", { status: 403 }); }
return new Response("Hello world"); }),);
import arcjet, { botCategories, detectBot } from "@arcjet/remix";import type { LoaderFunctionArgs } from "@remix-run/node";
const aj = arcjet({ key: process.env.ARCJET_KEY!, rules: [ detectBot({ mode: "LIVE", // configured with a list of bots to allow from // https://arcjet.com/bot-list - all other detected bots will be blocked allow: [ // filter a category to remove individual bots from our provided lists ...botCategories["CATEGORY:GOOGLE"].filter( (bot) => bot !== "GOOGLE_ADSBOT" && bot !== "GOOGLE_ADSBOT_MOBILE", ), ], }), ],});
export async function loader(args: LoaderFunctionArgs) { const decision = await aj.protect(args);
// Bots not in the allow list will be blocked if (decision.isDenied()) { throw new Response("Forbidden", { status: 403, statusText: "Forbidden" }); }
return null;}
import arcjet, { botCategories, detectBot } from "@arcjet/remix";
const aj = arcjet({ key: process.env.ARCJET_KEY, rules: [ detectBot({ mode: "LIVE", // configured with a list of bots to allow from // https://arcjet.com/bot-list - all other detected bots will be blocked allow: [ // filter a category to remove individual bots from our provided lists ...botCategories["CATEGORY:GOOGLE"].filter( (bot) => bot !== "GOOGLE_ADSBOT" && bot !== "GOOGLE_ADSBOT_MOBILE", ), ], }), ],});
export async function loader(args) { const decision = await aj.protect(args);
// Bots not in the allow list will be blocked if (decision.isDenied()) { throw new Response("Forbidden", { status: 403, statusText: "Forbidden" }); }
return null;}
import arcjet, { botCategories, detectBot } from "@arcjet/next";
const aj = arcjet({ key: process.env.ARCJET_KEY, rules: [ detectBot({ mode: "LIVE", // configured with a list of bots to allow from // https://arcjet.com/bot-list - all other detected bots will be blocked allow: [ // filter a category to remove individual bots from our provided lists ...botCategories["CATEGORY:GOOGLE"].filter( (bot) => bot !== "GOOGLE_ADSBOT" && bot !== "GOOGLE_ADSBOT_MOBILE", ), ], }), ],});
export default async function handler(req, res) { const decision = await aj.protect(req);
if (decision.reason.isBot()) { if (decision.isDenied()) { return res.status(403).json({ error: "Forbidden", // Useful for debugging, but don't return these to the client in // production denied: decision.reason.denied, }); } }
res.status(200).json({ name: "Hello world" });}
import arcjet, { botCategories, detectBot } from "@arcjet/next";import type { NextApiRequest, NextApiResponse } from "next";
const aj = arcjet({ key: process.env.ARCJET_KEY!, rules: [ detectBot({ mode: "LIVE", // configured with a list of bots to allow from // https://arcjet.com/bot-list - all other detected bots will be blocked allow: [ // filter a category to remove individual bots from our provided lists ...botCategories["CATEGORY:GOOGLE"].filter( (bot) => bot !== "GOOGLE_ADSBOT" && bot !== "GOOGLE_ADSBOT_MOBILE", ), ], }), ],});
export default async function handler( req: NextApiRequest, res: NextApiResponse,) { const decision = await aj.protect(req);
if (decision.reason.isBot()) { if (decision.isDenied()) { return res.status(403).json({ error: "Forbidden", // Useful for debugging, but don't return these to the client in // production denied: decision.reason.denied, }); } }
res.status(200).json({ name: "Hello world" });}
import arcjet, { botCategories, detectBot } from "@arcjet/next";import { NextResponse } from "next/server";
const aj = arcjet({ key: process.env.ARCJET_KEY!, rules: [ detectBot({ mode: "LIVE", // configured with a list of bots to allow from // https://arcjet.com/bot-list - all other detected bots will be blocked allow: [ // filter a category to remove individual bots from our provided lists ...botCategories["CATEGORY:GOOGLE"].filter( (bot) => bot !== "GOOGLE_ADSBOT" && bot !== "GOOGLE_ADSBOT_MOBILE", ), ], }), ],});
export async function POST(req: Request) { const decision = await aj.protect(req);
if (decision.reason.isBot()) { if (decision.isDenied()) { return NextResponse.json( { error: "You are a bot!", // Useful for debugging, but don't return these to the client in // production denied: decision.reason.denied, }, { status: 403 }, ); } }
return NextResponse.json({ message: "Hello world", });}
import arcjet, { botCategories, detectBot } from "@arcjet/next";import { NextResponse } from "next/server";
const aj = arcjet({ key: process.env.ARCJET_KEY, rules: [ detectBot({ mode: "LIVE", // configured with a list of bots to allow from // https://arcjet.com/bot-list - all other detected bots will be blocked allow: [ // filter a category to remove individual bots from our provided lists ...botCategories["CATEGORY:GOOGLE"].filter( (bot) => bot !== "GOOGLE_ADSBOT" && bot !== "GOOGLE_ADSBOT_MOBILE", ), ], }), ],});
export async function POST(req) { const decision = await aj.protect(req);
if (decision.reason.isBot()) { if (decision.isDenied()) { return NextResponse.json( { error: "You are a bot!", // Useful for debugging, but don't return these to the client in // production denied: decision.reason.denied, }, { status: 403 }, ); } }
return NextResponse.json({ message: "Hello world", });}
import { env } from "$env/dynamic/private";import arcjet, { botCategories, detectBot } from "@arcjet/sveltekit";import { error } from "@sveltejs/kit";
const aj = arcjet({ key: env.ARCJET_KEY, // Get your site key from https://app.arcjet.com rules: [ detectBot({ mode: "LIVE", // configured with a list of bots to allow from // https://arcjet.com/bot-list - all other detected bots will be blocked allow: [ // filter a category to remove individual bots from our provided lists ...botCategories["CATEGORY:GOOGLE"].filter( (bot) => bot !== "GOOGLE_ADSBOT" && bot !== "GOOGLE_ADSBOT_MOBILE", ), ], }), ],});
export async function handle({ event, resolve }) { const decision = await aj.protect(event);
// Bots not in the allow list will be blocked if (decision.isDenied()) { return error(403, "You are a bot!"); }
return resolve(event);}
import { env } from "$env/dynamic/private";import arcjet, { botCategories, detectBot } from "@arcjet/sveltekit";import { error, type RequestEvent } from "@sveltejs/kit";
const aj = arcjet({ key: env.ARCJET_KEY!, // Get your site key from https://app.arcjet.com rules: [ detectBot({ mode: "LIVE", // configured with a list of bots to allow from // https://arcjet.com/bot-list - all other detected bots will be blocked allow: [ // filter a category to remove individual bots from our provided lists ...botCategories["CATEGORY:GOOGLE"].filter( (bot) => bot !== "GOOGLE_ADSBOT" && bot !== "GOOGLE_ADSBOT_MOBILE", ), ], }), ],});
export async function handle({ event, resolve,}: { event: RequestEvent; resolve: (event: RequestEvent) => Response | Promise<Response>;}): Promise<Response> { const decision = await aj.protect(event);
// Bots not in the allow list will be blocked if (decision.isDenied()) { return error(403, "You are a bot!"); }
return resolve(event);}
Bot verification
Requests analyzed by Arcjet on Pro or Enterprise
plans include automatic bot verification. For allow
rules, Arcjet verifies the
authenticity of detected bots by checking IP data and performing reverse DNS
lookups.
This helps protect against spoofed bots where clients pretend to be someone else.
Example: Allowing Google
This will allow Google bots and verify their authenticity.
detectBot({ mode: "LIVE", // will block requests. Use "DRY_RUN" to log only // Allow Google, and block all other bots allow: [ "GOOGLE_CRAWLER", ],}),
When a request claims to be Googlebot, Arcjet will check if the IP truly belongs
to Google. If it does, the request will be marked as verified: true
. If not,
it will be marked as spoofed: true
.
You can check for this in your code and deny the request if it is spoofed.
function isSpoofed(result: ArcjetRuleResult) { return ( // You probably don't want DRY_RUN rules resulting in a denial // since they are generally used for evaluation purposes but you // could log here. result.state !== "DRY_RUN" && result.reason.isBot() && result.reason.isSpoofed() );}
// ...const decision = await aj.protect(req);// ...
if (decision.results.some(isSpoofed)) { // Return a 403 or similar response}
Check for spoofed bots
This will check if the bot is spoofed. You would usually return a 403 or similar response to block the request.
for (const { reason } of decision.results) { if (reason.isBot() && reason.isSpoofed()) { console.log("Detected spoofed bot", reason.spoofed); // Return a 403 or similar response }}
Check bot verification
This will check if the bot is verified.
for (const { reason } of decision.results) { if (reason.isBot() && reason.isVerified()) { console.log("Verified bot", reason.verified); // Allow the request }}
Testing
Arcjet runs the same in any environment, including locally and in CI. You can
use the mode
set to DRY_RUN
to log the results of rule execution without
blocking any requests.
We have an example test framework you can use to automatically test your rules. Arcjet can also be triggered based using a sample of your traffic.
See the Testing section of the docs for details.
Examples
Protecting a page
You can protect a Next.js page from bots by calling the Arcjet SDK from within the page loader:
Protecting an app router page within the handler itself is not currently supported, but you can set up a matcher on the middleware instead:
import arcjet, { createMiddleware, detectBot } from "@arcjet/next";export const config = { // The matcher runs just on the /hello pages route matcher: ["/hello"],};const aj = arcjet({ key: process.env.ARCJET_KEY!, rules: [ detectBot({ mode: "LIVE", allow: [], // "allow none" will block all detected bots }), ],});// Pass any existing middleware with the optional existingMiddleware propexport default createMiddleware(aj);
Protecting an app router page within the handler itself is not currently supported, but you can set up a matcher on the middleware instead:
import arcjet, { createMiddleware, detectBot } from "@arcjet/next";export const config = { // The matcher runs just on the /hello pages route matcher: ["/hello"],};const aj = arcjet({ key: process.env.ARCJET_KEY, rules: [ detectBot({ mode: "LIVE", allow: [], // "allow none" will block all detected bots }), ],});// Pass any existing middleware with the optional existingMiddleware propexport default createMiddleware(aj);
import arcjet, { detectBot } from "@arcjet/next";import Error from "next/error";import Head from "next/head";import React from "react";
const aj = arcjet({ key: process.env.ARCJET_KEY, rules: [ detectBot({ mode: "DRY_RUN", allow: [], // "allow none" will block all detected bots }), ],});
// getServerSideProps is called on the server before rendering the pageexport const getServerSideProps = async (context) => { const decision = await aj.protect(context.req); console.log("decision", decision);
if (decision.isDenied()) { return { props: { pageProps: { errorCode: 403, errorText: "Access denied" } }, }; }
return { props: { pageProps: { errorCode: false, errorText: "" } } };};
export default function Page({ pageProps }) { // If there is an error, render the Next.js error page if (pageProps.errorCode) { return ( <Error statusCode={pageProps.errorCode} title={pageProps.errorText} /> ); } return ( <> <Head> <title>Page</title> <meta name="viewport" content="width=device-width, initial-scale=1" /> </Head> <main> <div> <h2>Hello</h2> </div> </main> </> );}
import arcjet, { detectBot } from "@arcjet/next";import type { GetServerSideProps, InferGetServerSidePropsType } from "next";import Error from "next/error";import Head from "next/head";import React from "react";
const aj = arcjet({ key: process.env.ARCJET_KEY!, rules: [ detectBot({ mode: "DRY_RUN", allow: [], // "allow none" will block all detected bots }), ],});
type pageProps = { errorCode: number | false; errorText: string;};
// getServerSideProps is called on the server before rendering the pageexport const getServerSideProps = (async (context) => { const decision = await aj.protect(context.req); console.log("decision", decision);
if (decision.isDenied()) { return { props: { pageProps: { errorCode: 403, errorText: "Access denied" } }, }; }
return { props: { pageProps: { errorCode: false, errorText: "" } } };}) satisfies GetServerSideProps<{ pageProps: pageProps;}>;
export default function Page({ pageProps,}: InferGetServerSidePropsType<typeof getServerSideProps>) { // If there is an error, render the Next.js error page if (pageProps.errorCode) { return ( <Error statusCode={pageProps.errorCode} title={pageProps.errorText} /> ); } return ( <> <Head> <title>Page</title> <meta name="viewport" content="width=device-width, initial-scale=1" /> </Head> <main> <div> <h2>Hello</h2> </div> </main> </> );}
Wrap existing handler
All the examples on this page show how you can inspect the decision to control
what to do next. However, if you just wish to send a generic 403 Forbidden
response you can delegate this to Arcjet by wrapping your handler withArcjet
.
For both the Node or Edge runtime:
import arcjet, { detectBot, withArcjet } from "@arcjet/next";import { NextResponse } from "next/server";
const aj = arcjet({ key: process.env.ARCJET_KEY!, rules: [ detectBot({ mode: "LIVE", allow: [], // "allow none" will block all detected bots }), ],});
export const GET = withArcjet(aj, async (req: Request) => { return NextResponse.json({ message: "Hello world", });});
For both the Node or Edge runtime:
import arcjet, { detectBot, withArcjet } from "@arcjet/next";import { NextResponse } from "next/server";
const aj = arcjet({ key: process.env.ARCJET_KEY, rules: [ detectBot({ mode: "LIVE", allow: [], // "allow none" will block all detected bots }), ],});
export const GET = withArcjet(aj, async (req) => { return NextResponse.json({ message: "Hello world", });});
For the Node (default) runtime:
import arcjet, { detectBot, withArcjet } from "@arcjet/next";import type { NextApiRequest, NextApiResponse } from "next";
export const config = { runtime: "edge",};
const aj = arcjet({ key: process.env.ARCJET_KEY!, rules: [ detectBot({ mode: "LIVE", allow: [], // "allow none" will block all detected bots }), ],});
export default withArcjet( aj, async (req: NextApiRequest, res: NextApiResponse) => { res.status(200).json({ name: "Hello world" }); },);
For the Edge runtime:
import arcjet, { detectBot, withArcjet } from "@arcjet/next";import { NextRequest, NextResponse } from "next/server";
export const config = { runtime: "edge",};
const aj = arcjet({ key: process.env.ARCJET_KEY!, rules: [ detectBot({ mode: "LIVE", allow: [], // "allow none" will block all detected bots }), ],});
export default withArcjet(aj, async (req: NextRequest) => { return NextResponse.json({ message: "Hello world", });});
For the Node (default) runtime:
import arcjet, { detectBot, withArcjet } from "@arcjet/next";
export const config = { runtime: "edge",};
const aj = arcjet({ key: process.env.ARCJET_KEY, rules: [ detectBot({ mode: "LIVE", allow: [], // "allow none" will block all detected bots }), ],});
export default withArcjet(aj, async (req, res) => { res.status(200).json({ name: "Hello world" });});
For the Edge runtime:
import arcjet, { detectBot, withArcjet } from "@arcjet/next";import { NextResponse } from "next/server";
export const config = { runtime: "edge",};
const aj = arcjet({ key: process.env.ARCJET_KEY, rules: [ detectBot({ mode: "LIVE", allow: [], // "allow none" will block all detected bots }), ],});
export default withArcjet(aj, async (req) => { return NextResponse.json({ message: "Hello world", });});
Edge Functions
Arcjet works in Edge Functions and with the Edge Runtime.
import arcjet, { detectBot } from "@arcjet/next";
export const config = { runtime: "edge",};
const aj = arcjet({ key: process.env.ARCJET_KEY, rules: [ detectBot({ mode: "LIVE", allow: [], // "allow none" will block all detected bots }), ],});
export default async function handler(req, res) { const decision = await aj.protect(req);
if (decision.isDenied()) { return res.status(403).json({ error: "You are a bot!" }); }
res.status(200).json({ name: "Hello world" });}
import arcjet, { detectBot } from "@arcjet/next";import type { NextApiRequest, NextApiResponse } from "next";
export const config = { runtime: "edge",};
const aj = arcjet({ key: process.env.ARCJET_KEY!, rules: [ detectBot({ mode: "LIVE", allow: [], // "allow none" will block all detected bots }), ],});
export default async function handler( req: NextApiRequest, res: NextApiResponse,) { const decision = await aj.protect(req);
if (decision.isDenied()) { return res.status(403).json({ error: "You are a bot!" }); }
res.status(200).json({ name: "Hello world" });}
import arcjet, { detectBot } from "@arcjet/next";import { NextRequest, NextResponse } from "next/server";
export const config = { runtime: "edge",};
const aj = arcjet({ key: process.env.ARCJET_KEY!, rules: [ detectBot({ mode: "LIVE", allow: [], // "allow none" will block all detected bots }), ],});
export default async function handler(req: NextRequest, res: NextResponse) { const decision = await aj.protect(req);
if (decision.isDenied()) { return NextResponse.json( { error: "You are a bot!", }, { status: 403, }, ); }
return NextResponse.json({ message: "Hello world", });}
import arcjet, { detectBot } from "@arcjet/next";import { NextResponse } from "next/server";
export const config = { runtime: "edge",};
const aj = arcjet({ key: process.env.ARCJET_KEY, rules: [ detectBot({ mode: "LIVE", allow: [], // "allow none" will block all detected bots }), ],});
export async function GET(req) { const decision = await aj.protect(req);
if (decision.isDenied()) { return NextResponse.json( { error: "You are a bot!", }, { status: 403, }, ); }
return NextResponse.json({ message: "Hello world", });}