@arcjet/next

中文文档
1.15.0发布于 2026/10/29Apache-2.0TypeScriptES Module构建来源已验证近 30 天下载 30万

Arcjet runtime security SDK for Next.js — bot protection, rate limiting, prompt injection detection, PII blocking, and WAF

原始使用文档
文档目录22 节
  1. Why Arcjet?
  2. Getting started
  3. Quick setup with an AI agent
  4. Manual setup
  5. Features
  6. Quick start
  7. Prompt injection detection
  8. Bot protection
  9. Bot categories
  10. Verified vs spoofed bots
  11. Rate limiting
  12. Sensitive information detection
  13. Shield WAF
  14. Email validation
  15. Request filters
  16. Block by country
  17. Block VPN and proxy traffic
  18. IP analysis
  19. Custom characteristics
  20. Server components and actions
  21. Best practices
  22. License
Arcjet Logo

@arcjet/next

npm badge

Arcjet is the runtime security platform that ships in your AI code. Detect prompt injection, authorize agent tool calls, redact sensitive data, and block bots and abuse. Real-time security building blocks you call inside your app, before an action happens.

This is the Arcjet SDK for Next.js request protection — use it to protect HTTP route handlers and API endpoints. If you need to protect AI agent tool calls, MCP server handlers, or background jobs (anything without an HTTP request), see @arcjet/guard.

Why Arcjet?

Your app's AI features and agents take real actions, calling tools, reading data, hitting APIs. Arcjet runs inside that code and lets you enforce security on each action in real time, then audit what happened

Getting started

Quick setup with an AI agent

  1. Log in with the CLI:
    npx @arcjet/cli auth login
    
  2. Install versioned Agent Skills so your coding agent matches this SDK:
    npx @tanstack/intent@latest install
    
  3. Tell your agent what to protect — it handles the rest.

Manual setup

  1. Log in with the CLI (or at app.arcjet.com):
    npx @arcjet/cli auth login
    
  2. npm install @arcjet/next
  3. Set ARCJET_KEY=ajkey_yourkey in .env.local
  4. Add Arcjet to your route — see the quick start below

npm package | GitHub source | Full docs | Other SDKs

Features

All features below are available with @arcjet/next for request protection. For guard protection (tool calls, MCP servers, queues) see @arcjet/guard.

Feature@arcjet/next@arcjet/guard
Rate Limiting✅✅
Prompt Injection Detection✅✅
Sensitive Information Detection✅✅
Bot Protection✅—
Shield WAF✅—
Email Validation✅—
Signup Form Protection✅—
Request Filters✅—
IP Analysis✅—
Custom Rules—✅
  • 🔒 Prompt Injection Detection — detect and block prompt injection attacks before they reach your LLM.
  • 🤖 Bot Protection — stop scrapers, credential stuffers, and AI crawlers from abusing your endpoints.
  • 🛑 Rate Limiting — token bucket, fixed window, and sliding window algorithms; model AI token budgets per user.
  • 🕵️ Sensitive Information Detection — block PII, credit cards, and custom patterns from entering your AI pipeline.
  • 🛡️ Shield WAF — protect against SQL injection, XSS, and other common web attacks.
  • 📧 Email Validation — block disposable, invalid, and undeliverable addresses at signup.
  • 📝 Signup Form Protection — combines bot protection, email validation, and rate limiting to protect your signup forms.
  • 🎯 Request Filters — expression-based rules on IP, path, headers, and custom fields.
  • 🌐 IP Analysis — geolocation, ASN, VPN, proxy, Tor, and hosting detection included with every request.
  • 🚅 Nosecone — set security headers such as Content-Security-Policy (CSP).

Quick start

This example protects a Next.js AI chat route: blocking automated clients that inflate costs, enforcing per-user token budgets, detecting sensitive information in messages, and blocking prompt injection attacks before they reach the model.

Install the Vercel AI SDK, an AI provider, and the Rampart sensitive information backend:

npm install ai @ai-sdk/openai @arcjet/sensitive-info-rampart

Create a new API route at /app/api/chat/route.ts:

import { openai } from "@ai-sdk/openai";
import arcjet, {
  detectBot,
  detectPromptInjection,
  sensitiveInfo,
  shield,
  tokenBucket,
} from "@arcjet/next";
import { rampart } from "@arcjet/sensitive-info-rampart";
import type { UIMessage } from "ai";
import { convertToModelMessages, isTextUIPart, streamText } from "ai";

const aj = arcjet({
  key: process.env.ARCJET_KEY!, // Get your key with: npx @arcjet/cli sites get-key
  // Track budgets per user — replace "userId" with any stable identifier
  characteristics: ["userId"],
  rules: [
    // Shield protects against common web attacks e.g. SQL injection
    shield({ mode: "LIVE" }),
    // Block all automated clients — bots inflate AI costs
    detectBot({
      mode: "LIVE", // Blocks requests. Use "DRY_RUN" to log only
      allow: [], // Block all bots. See https://arcjet.com/bot-list
    }),
    // Enforce budgets to control AI costs. Adjust rates and limits as needed.
    tokenBucket({
      mode: "LIVE",
      refillRate: 2_000, // Refill 2,000 tokens per hour
      interval: "1h",
      capacity: 5_000, // Maximum 5,000 tokens in the bucket
    }),
    // Block messages containing sensitive information to prevent data leaks
    sensitiveInfo({
      mode: "LIVE",
      // Block PII types that should never appear in AI prompts.
      // Remove types your app legitimately handles (e.g. EMAIL for a support bot).
      deny: ["CREDIT_CARD_NUMBER", "EMAIL"],
      // Detect PII on-device with the Rampart model
      backend: rampart(),
    }),
    // Detect prompt injection attacks before they reach your AI model
    detectPromptInjection({
      mode: "LIVE",
    }),
  ],
});

export async function POST(req: Request) {
  const userId = "user-123"; // Replace with your session/auth lookup
  const { messages }: { messages: UIMessage[] } = await req.json();
  const modelMessages = await convertToModelMessages(messages);

  // Estimate token cost: ~1 token per 4 characters of text (rough heuristic).
  // For accurate counts use https://www.npmjs.com/package/tiktoken
  const totalChars = modelMessages.reduce((sum, m) => {
    const content =
      typeof m.content === "string" ? m.content : JSON.stringify(m.content);
    return sum + content.length;
  }, 0);
  const estimate = Math.ceil(totalChars / 4);

  // Extract the most recent user message to scan for injection and PII.
  // Pass all messages if you want to scan the full conversation.
  const lastMessage: string = (messages.at(-1)?.parts ?? [])
    .filter(isTextUIPart)
    .map((p) => p.text)
    .join(" ");

  const decision = await aj.protect(req, {
    userId,
    requested: estimate,
    sensitiveInfoValue: lastMessage,
    detectPromptInjectionMessage: lastMessage,
  });

  if (decision.isDenied()) {
    if (decision.reason.isBot()) {
      return new Response("Automated clients are not permitted", {
        status: 403,
      });
    } else if (decision.reason.isRateLimit()) {
      return new Response("AI usage limit exceeded", { status: 429 });
    } else if (decision.reason.isSensitiveInfo()) {
      return new Response("Sensitive information detected", { status: 400 });
    } else if (decision.reason.isPromptInjection()) {
      return new Response(
        "Prompt injection detected — please rephrase your message",
        { status: 400 },
      );
    } else {
      return new Response("Forbidden", { status: 403 });
    }
  }

  const result = await streamText({
    model: openai("gpt-4o"),
    messages: modelMessages,
  });

  return result.toUIMessageStreamResponse();
}

Rampart loads a native ONNX runtime, so add @arcjet/sensitive-info-rampart, @huggingface/transformers, and onnxruntime-node to serverExternalPackages in next.config.js and run the route on the Node.js runtime (the default). See Bundlers and frameworks.

For the full reference, see the Arcjet Next.js SDK docs.

Prompt injection detection

Detect and block prompt injection attacks — attempts to override your AI model's instructions — before they reach your model. Pass the user's message via detectPromptInjectionMessage on each protect() call.

import arcjet, { detectPromptInjection } from "@arcjet/next";
import { NextResponse } from "next/server";

const aj = arcjet({
  key: process.env.ARCJET_KEY!,
  rules: [
    detectPromptInjection({
      mode: "LIVE", // Blocks requests. Use "DRY_RUN" to log only
    }),
  ],
});

export async function POST(request: Request) {
  const { message } = await request.json();

  const decision = await aj.protect(request, {
    detectPromptInjectionMessage: message,
  });

  if (decision.isDenied() && decision.reason.isPromptInjection()) {
    return NextResponse.json(
      { error: "Prompt injection detected — please rephrase your message" },
      { status: 400 },
    );
  }

  // Forward to your AI model...
}

Bot protection

Arcjet allows you to configure a list of bots to allow or deny. Specifying allow means all other bots are denied. An empty allow list blocks all bots.

Available categories: CATEGORY:ACADEMIC, CATEGORY:ADVERTISING, CATEGORY:AI, CATEGORY:AMAZON, CATEGORY:APPLE, CATEGORY:ARCHIVE, CATEGORY:BOTNET, CATEGORY:FEEDFETCHER, CATEGORY:GOOGLE, CATEGORY:META, CATEGORY:MICROSOFT, CATEGORY:MONITOR, CATEGORY:OPTIMIZER, CATEGORY:PREVIEW, CATEGORY:PROGRAMMATIC, CATEGORY:SEARCH_ENGINE, CATEGORY:SLACK, CATEGORY:SOCIAL, CATEGORY:TOOL, CATEGORY:UNKNOWN, CATEGORY:VERCEL, CATEGORY:WEBHOOK, CATEGORY:YAHOO. You can also allow or deny specific bots by name.

import arcjet, { detectBot } from "@arcjet/next";
import { isSpoofedBot } from "@arcjet/inspect";
import { NextResponse } from "next/server";

const aj = arcjet({
  key: process.env.ARCJET_KEY!,
  rules: [
    detectBot({
      mode: "LIVE", // Blocks requests. Use "DRY_RUN" to log only
      allow: [
        "CATEGORY:SEARCH_ENGINE", // Google, Bing, etc
        // Uncomment to allow these other common bot categories:
        // "CATEGORY:MONITOR",  // Uptime monitoring services
        // "CATEGORY:PREVIEW",  // Link previews e.g. Slack, Discord
        // See the full list at https://arcjet.com/bot-list
      ],
    }),
  ],
});

export async function GET(request: Request) {
  const decision = await aj.protect(request);

  if (decision.isDenied() && decision.reason.isBot()) {
    return NextResponse.json({ error: "No bots allowed" }, { status: 403 });
  }

  // Verifies the authenticity of common bots using IP data.
  // Verification isn't always possible, so check the results separately.
  // https://docs.arcjet.com/bot-protection/reference#bot-verification
  if (decision.results.some(isSpoofedBot)) {
    return NextResponse.json({ error: "Forbidden" }, { status: 403 });
  }

  return NextResponse.json({ message: "Hello world" });
}

Bot categories

Bots can be configured by category and/or by specific bot name. For example, to allow search engines and the OpenAI crawler, but deny all other bots:

detectBot({
  mode: "LIVE",
  allow: ["CATEGORY:SEARCH_ENGINE", "OPENAI_CRAWLER_SEARCH"],
});

Verified vs spoofed bots

Bots claiming to be well-known crawlers (e.g. Googlebot) are verified by checking their IP address against the known IP ranges for that bot. If a bot fails verification, it is labeled as spoofed. Use isSpoofedBot from @arcjet/inspect to check:

import { isSpoofedBot } from "@arcjet/inspect";

if (decision.results.some(isSpoofedBot)) {
  return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}

Rate limiting

Arcjet supports token bucket, fixed window, and sliding window algorithms. Token buckets are ideal for controlling AI token budgets — set capacity to the max tokens a user can spend, refillRate to how many tokens are restored per interval, and deduct tokens per request via requested in protect(). The interval accepts strings ("1s", "1m", "1h", "1d") or seconds as a number. Use characteristics to track limits per user instead of per IP.

import arcjet, { tokenBucket } from "@arcjet/next";
import { NextResponse } from "next/server";

const aj = arcjet({
  key: process.env.ARCJET_KEY!,
  characteristics: ["userId"], // Track per user
  rules: [
    // Token bucket: ideal for controlling AI token costs
    tokenBucket({
      mode: "LIVE",
      refillRate: 2_000, // Refill 2,000 tokens per hour
      interval: "1h",
      capacity: 5_000, // Maximum 5,000 tokens in the bucket
    }),
  ],
});

const decision = await aj.protect(request, {
  userId: "user-123",
  requested: estimate, // Number of tokens to deduct
});

if (decision.isDenied() && decision.reason.isRateLimit()) {
  return NextResponse.json(
    { error: "AI usage limit exceeded" },
    { status: 429 },
  );
}

Sensitive information detection

Detect and block PII in request content on-device with @arcjet/sensitive-info-rampart, which runs the Rampart named-entity-recognition model locally, so no data leaves your environment. Pass the content to scan via sensitiveInfoValue on each protect() call. Rampart detects names, addresses, government and financial identifiers, email addresses, phone numbers, IP addresses, and card numbers. Add a recognizer to detect custom patterns.

npm install @arcjet/sensitive-info-rampart
import arcjet, { sensitiveInfo } from "@arcjet/next";
import { rampart } from "@arcjet/sensitive-info-rampart";
import { NextResponse } from "next/server";

const aj = arcjet({
  key: process.env.ARCJET_KEY!,
  rules: [
    sensitiveInfo({
      mode: "LIVE", // Blocks requests. Use "DRY_RUN" to log only
      deny: ["CREDIT_CARD_NUMBER", "EMAIL", "PHONE_NUMBER"],
      backend: rampart(),
    }),
  ],
});

export async function POST(request: Request) {
  const { message } = await request.json();

  const decision = await aj.protect(request, {
    sensitiveInfoValue: message,
  });

  if (decision.isDenied() && decision.reason.isSensitiveInfo()) {
    return NextResponse.json(
      { error: "Sensitive information detected" },
      { status: 400 },
    );
  }
}

Rampart loads a native ONNX runtime, so add @arcjet/sensitive-info-rampart, @huggingface/transformers, and onnxruntime-node to serverExternalPackages in next.config.js and run the route on the Node.js runtime (the default). See Bundlers and frameworks.

Shield WAF

Protect your application against common web attacks, including the OWASP Top 10.

import arcjet, { shield } from "@arcjet/next";

const aj = arcjet({
  key: process.env.ARCJET_KEY!,
  rules: [
    shield({
      mode: "LIVE", // Blocks requests. Use "DRY_RUN" to log only
    }),
  ],
});

Email validation

Validate and verify email addresses. Deny types: DISPOSABLE, FREE, NO_MX_RECORDS, NO_GRAVATAR, INVALID.

import arcjet, { validateEmail } from "@arcjet/next";
import { NextResponse } from "next/server";

const aj = arcjet({
  key: process.env.ARCJET_KEY!,
  rules: [
    validateEmail({
      mode: "LIVE",
      deny: ["DISPOSABLE", "INVALID", "NO_MX_RECORDS"],
    }),
  ],
});

export async function POST(request: Request) {
  const { email } = await request.json();

  const decision = await aj.protect(request, { email });

  if (decision.isDenied() && decision.reason.isEmail()) {
    return NextResponse.json(
      { error: "Invalid email address" },
      { status: 400 },
    );
  }
}

Request filters

Filter requests using expression-based rules against request properties (IP, headers, path, method, etc.).

import arcjet, { filter } from "@arcjet/next";

const aj = arcjet({
  key: process.env.ARCJET_KEY!,
  rules: [
    filter({
      mode: "LIVE",
      deny: ['ip.src == "1.2.3.4"', 'http.request.uri.path contains "/admin"'],
    }),
  ],
});

Block by country

Restrict access to specific countries — useful for licensing, compliance, or regional rollouts. The allow list denies all countries not listed:

filter({
  mode: "LIVE",
  // Allow only US traffic — all other countries are denied
  allow: ['ip.src.country == "US"'],
});

Block VPN and proxy traffic

Prevent anonymized traffic from accessing sensitive endpoints — useful for fraud prevention, enforcing geo-restrictions, and reducing abuse:

filter({
  mode: "LIVE",
  deny: [
    "ip.src.vpn", // VPN services
    "ip.src.proxy", // Open proxies
    "ip.src.tor", // Tor exit nodes
  ],
});

For more nuanced handling, use decision.ip helpers after calling protect():

const decision = await aj.protect(request);

if (decision.ip.isVpn() || decision.ip.isTor()) {
  return NextResponse.json(
    { error: "VPN traffic not allowed" },
    { status: 403 },
  );
}

See the Request Filters docs, IP Geolocation blueprint, and VPN/Proxy Detection blueprint for more details.

IP analysis

Arcjet enriches every request with IP metadata. Use these helpers to make policy decisions based on network signals:

const decision = await aj.protect(request);

if (decision.ip.isHosting()) {
  // Requests from cloud/hosting providers are often automated.
  // https://docs.arcjet.com/blueprints/vpn-proxy-detection
  return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}

if (decision.ip.isVpn() || decision.ip.isProxy() || decision.ip.isTor()) {
  // Handle VPN/proxy traffic according to your policy
}

// Access geolocation and network details
console.log(decision.ip.country, decision.ip.city, decision.ip.asn);

Custom characteristics

Track and limit requests by any stable identifier — user ID, API key, session, etc. — rather than IP address alone.

const aj = arcjet({
  key: process.env.ARCJET_KEY!,
  characteristics: ["userId"], // Declare at the SDK level
  rules: [
    tokenBucket({
      mode: "LIVE",
      refillRate: 2_000,
      interval: "1h",
      capacity: 5_000,
    }),
  ],
});

// Pass the characteristic value at request time
const decision = await aj.protect(request, {
  userId: "user-123", // Replace with your actual user ID
  requested: estimate,
});

Server components and actions

@arcjet/next exports a request() helper that works anywhere you don't have direct access to the incoming Request object e.g. server actions.

import arcjet, { shield } from "@arcjet/next";
import { request } from "@arcjet/next";

const aj = arcjet({
  key: process.env.ARCJET_KEY!,
  rules: [shield({ mode: "LIVE" })],
});

export async function myServerAction() {
  "use server";
  const req = await request();
  const decision = await aj.protect(req);

  if (decision.isDenied()) {
    throw new Error("Forbidden");
  }

  // ...
}

Best practices

See the Arcjet best practices for detailed guidance. Key recommendations:

Create a single client instance and reuse it with withRule() for route-specific rules. The SDK caches decisions and configuration, so creating a new instance per request wastes that work.

// lib/arcjet.ts — create once, import everywhere
import arcjet, { shield } from "@arcjet/next";

export default arcjet({
  key: process.env.ARCJET_KEY!,
  rules: [
    shield({ mode: "LIVE" }), // base rules applied to every request
  ],
});
// app/api/chat/route.ts — extend per-route with withRule()
import aj from "@/lib/arcjet";
import { detectBot, tokenBucket } from "@arcjet/next";

const routeAj = aj.withRule(detectBot({ mode: "LIVE", allow: [] })).withRule(
  tokenBucket({
    mode: "LIVE",
    refillRate: 2_000,
    interval: "1h",
    capacity: 5_000,
  }),
);

export async function POST(req: Request) {
  const decision = await routeAj.protect(req, { requested: 500 });
  // ...
}

Other recommendations:

  • Call protect() in route handlers, not middleware. Middleware lacks route context, making it hard to apply route-specific rules or customize responses.
  • Call protect() once per request. Calling it in both middleware and a handler doubles the work and can produce unexpected results.
  • Start rules in DRY_RUN mode to observe behavior before switching to LIVE. This lets you tune thresholds without affecting real traffic.
  • Configure proxies if your app runs behind a load balancer or reverse proxy so Arcjet resolves the real client IP:
    arcjet({
      key: process.env.ARCJET_KEY!,
      rules: [],
      proxies: ["100.100.100.100"],
    });
    
  • Handle errors explicitly. protect() never throws — on error it returns an ERROR result. Fail open by logging and allowing the request:
    if (decision.isErrored()) {
      console.error("Arcjet error", decision.reason.message);
      // allow the request to proceed
    }
    

License

Apache License, Version 2.0 © Arcjet Labs, Inc.

版本与发布记录

@arcjet/next 共发布 79 个版本,首次发布于 2023/12/08;过去 12 个月发布了 30 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
1.15.0latest2026/10/298 天前
1.14.12026/10/0730 天前
1.14.02026/10/021 个月前
1.13.02026/09/171 个月前
1.12.02026/09/091 个月前
1.11.02026/08/272 个月前

其他发布通道:rc → 1.10.0-rc.1。

关于 @arcjet/next 的常见问题

@arcjet/next 是什么?

Arcjet runtime security SDK for Next.js — bot protection, rate limiting, prompt injection detection, PII blocking, and WAF

如何安装 @arcjet/next?

在项目目录运行 npm install @arcjet/next,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:next(>=13)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@arcjet/next 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@arcjet/next 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@arcjet/next 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=22.21.0 <23 || >=24.5.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@arcjet/next 可以商用吗?

@arcjet/next 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@arcjet/next 的下载量有多少?

根据 npm 官方下载统计,@arcjet/next 在 2026/10/07 – 2026/11/05 这 30 天内被下载 300,335 次,日均约 10,011 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@arcjet/next 还在维护吗?

最新版本 1.15.0 发布于 2026/10/29(8 天前);至今共发布 79 个版本,其中过去 12 个月发布了 30 个;首次发布于 2023/12/08。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。