Get started with Next.js
Arcjet is the runtime security platform that ships with your code. Enforce budgets, stop prompt injection, detect bots, and protect personal information with Arcjet’s AI security building blocks.
This guide shows you how to protect an application with Arcjet by blocking automated clients that inflate costs and enforcing per-user token budgets.
1. Install Arcjet
Section titled “1. Install Arcjet”In your project root, run the following:
npm i @arcjet/nextpnpm add @arcjet/nextyarn add @arcjet/nextRequirements
Section titled “Requirements”- Next.js 15 or 16.
- CommonJS is not supported. Arcjet is ESM only.
2. Set your key
Section titled “2. Set your key”Create a free Arcjet account then follow the instructions to add a site and get a key.
Add your key to a .env.local file in your project root.
ARCJET_KEY=ajkey_yourkeyARCJET_ENV=development3. Configure
Section titled “3. Configure”This configures Arcjet to protect your AI application: block automated clients that inflate costs, and enforce per-user token budgets.
This example uses the Vercel AI SDK. Install it along with an AI provider:
npm install ai @ai-sdk/openaipnpm add ai @ai-sdk/openaiyarn add ai @ai-sdk/openaiCreate 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 type { UIMessage } from "ai";import { convertToModelMessages, isTextUIPart, streamText } from "ai";
const aj = arcjet({ key: process.env.ARCJET_KEY!, // Get your site key from https://console.arcjet.com // Track budgets per user – replace "userId" with any stable identifier characteristics: ["userId"], rules: [ // Shield protects against common web attacks such as 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", // Blocks requests. Use "DRY_RUN" to log only 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", // Blocks requests. Use "DRY_RUN" to log only // Block PII types that should never appear in AI prompts. // Remove types your app legitimately handles (for example, EMAIL for a support bot). deny: ["CREDIT_CARD_NUMBER", "EMAIL"], }), // Detect prompt injection attacks before they reach your AI model detectPromptInjection({ mode: "LIVE", // Blocks requests. Use "DRY_RUN" to log only }), ],});
export async function POST(req: Request) { // Replace with your session/auth lookup to get a stable user ID const userId = "user-123"; 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);
// Check the most recent user message for sensitive information and prompt injection. // Pass the full conversation if you want to scan all messages. const lastMessage: string = (messages.at(-1)?.parts ?? []) .filter(isTextUIPart) .map((p) => p.text) .join(" ");
// Check with Arcjet before calling the AI provider 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 – 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();}Create a new API route at /app/api/chat/route.js:
import { openai } from "@ai-sdk/openai";import arcjet, { detectBot, detectPromptInjection, sensitiveInfo, shield, tokenBucket,} from "@arcjet/next";import { convertToModelMessages, isTextUIPart, streamText } from "ai";
const aj = arcjet({ key: process.env.ARCJET_KEY, // Get your site key from https://console.arcjet.com // Track budgets per user – replace "userId" with any stable identifier characteristics: ["userId"], rules: [ // Shield protects against common web attacks such as 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", // Blocks requests. Use "DRY_RUN" to log only 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", // Blocks requests. Use "DRY_RUN" to log only // Block PII types that should never appear in AI prompts. // Remove types your app legitimately handles (for example, EMAIL for a support bot). deny: ["CREDIT_CARD_NUMBER", "EMAIL"], }), // Detect prompt injection attacks before they reach your AI model detectPromptInjection({ mode: "LIVE", // Blocks requests. Use "DRY_RUN" to log only }), ],});
export async function POST(req) { // Replace with your session/auth lookup to get a stable user ID const userId = "user-123"; const { messages } = 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);
// Check the most recent user message for sensitive information and prompt injection. // Pass the full conversation if you want to scan all messages. const lastMessage = (messages.at(-1)?.parts ?? []) .filter(isTextUIPart) .map((p) => p.text) .join(" ");
// Check with Arcjet before calling the AI provider 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 – 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();}And create a new page at /app/page.tsx:
"use client";
import { useChat } from "@ai-sdk/react";import { useState } from "react";
export default function Chat() { const [input, setInput] = useState(""); const [errorMessage, setErrorMessage] = useState<string | null>(null); const { messages, sendMessage } = useChat({ onError: async (e) => setErrorMessage(e.message), }); return ( <div className="flex flex-col w-full max-w-md py-24 mx-auto stretch"> {messages.map((message) => ( <div key={message.id} className="whitespace-pre-wrap"> {message.role === "user" ? "User: " : "AI: "} {message.parts.map((part, i) => { switch (part.type) { case "text": return <div key={`${message.id}-${i}`}>{part.text}</div>; } })} </div> ))}
{errorMessage && ( <div className="text-red-500 text-sm mb-4">{errorMessage}</div> )}
<form onSubmit={(e) => { e.preventDefault(); sendMessage({ text: input }); setInput(""); setErrorMessage(null); }} > <input className="fixed dark:bg-zinc-900 bottom-0 w-full max-w-md p-2 mb-8 border border-zinc-300 dark:border-zinc-800 rounded shadow-xl" value={input} placeholder="Say something..." onChange={(e) => setInput(e.currentTarget.value)} /> </form> </div> );}4. Start app
npm run devpnpm run devyarn run devThen start chatting with the AI in your app. Requests appear in your Arcjet dashboard in real time.
Try entering an email address to see the sensitive info detection in action, or sending many messages in a row to trigger the rate limit.
The requests also appear in the Arcjet dashboard.
Do I need to run any infrastructure, such as Redis?
No, Arcjet handles all the infrastructure for you so you don't need to worry about deploying global Redis clusters, designing data structures to track rate limits, or keeping security detection rules up to date.
What is the performance overhead?
Arcjet SDK tries to do as much as possible asynchronously and locally to minimize latency for each request. Where decisions can be made locally or previous decisions are cached in-memory, latency is usually <1ms.
When a call to the Cloud API is required, such as when tracking a rate limit in a serverless environment, there is some additional latency before a decision is made. The Cloud API has been designed for high performance and low latency, and is deployed to multiple regions around the world. The SDK will automatically use the closest region which means the total overhead is typically no more than 20-30ms, often significantly less.
What happens if Arcjet is unavailable?
Where a decision has been cached locally, such as blocking a client, Arcjet will continue to function even if the service is unavailable.
If a call to the Cloud API is needed and there is a network problem or Arcjet is unavailable, the default behavior is to fail open and allow the request. You have control over how to handle errors, including choosing to fail close if you prefer. See the reference docs for details.
How does Arcjet protect me against DDoS attacks?
Network layer attacks tend to be generic and high volume, so these are best handled by your hosting platform. Most cloud providers include network DDoS protection by default.
Arcjet sits closer to your application so it can understand the context. This is important because some types of traffic may not look like a DDoS attack, but can still have the same effect. For example, a customer making too many API requests and affecting other customers, or large numbers of signups from disposable email addresses.
Network-level DDoS protection tools find it difficult to protect against this type of traffic because they don't understand the structure of your application. Arcjet can help you to identify and block this traffic by integrating with your codebase and understanding the context of the request, such as the customer ID or the sensitivity of the API route.
Volumetric network attacks are best handled by your hosting provider. Application level attacks need to be handled by the application. That's where Arcjet helps.
What next?
Section titled “What next?”Get help
Section titled “Get help”Need help with anything? Email us or join our Discord to get support from our engineering team.