Sensitive information detection for Next.js
Arcjet Sensitive Information Detection protects against clients sending you sensitive information such as personally identifiable information (PII) that you do not wish to handle.
What is Arcjet?
Arcjet is the AI agent runtime security platform. Discover the agents running in your organization, enforce policy across every action, prompt, and tool call, and keep the evidence to prove what happened. Detect prompt injection, authorize agent tool calls, redact PII, and block bots and abuse.Quick start
Section titled “Quick start”This guide shows you how to configure Arcjet for a
1. Install Arcjet
Section titled “1. Install Arcjet”In your project root, install the SDK:
npm i @arcjet/next @arcjet/sensitive-info-rampart @arcjet/inspectpnpm add @arcjet/next @arcjet/sensitive-info-rampart @arcjet/inspectyarn add @arcjet/next @arcjet/sensitive-info-rampart @arcjet/inspect2. Set your key
Section titled “2. Set your key”Create a free Arcjet account. In the Arcjet
Console, select New actor, enter a name, and then select Create. Copy
the Actor key from the actor’s page. It starts with ajkey_.
The Console also shows a Project key that starts with aj_prj_key_. The
SDK can’t use the project key.
Add the actor key to a .env.local file in your project root.
ARCJET_KEY=ajkey_yourkey3. Protect a route
Section titled “3. Protect a route”Create a sensitive info detection rule that scans untrusted text before you
process it. Detection runs on-device with the
Rampart backend.
Agent integrations use localDetectSensitiveInfo from the Guard SDK. You can
change which entity types to detect. For details, see the
reference.
Create a new API route at /pages/api/arcjet.js:
import arcjet, { sensitiveInfo } from "@arcjet/next";import { rampart } from "@arcjet/sensitive-info-rampart";
const aj = arcjet({ key: process.env.ARCJET_KEY, rules: [ sensitiveInfo({ mode: "LIVE", // Will block requests, use "DRY_RUN" to log only // Detect names and email addresses. See the reference for the full list. deny: ["EMAIL", "GIVEN_NAME", "SURNAME"], // Run detection on-device with the Rampart NER model. backend: rampart(), }), ],});
export default async function handler(req, res) { const decision = await aj.protect(req, { sensitiveInfoValue: req.body, }); console.log("Arcjet decision", decision);
if (decision.isDenied() && decision.reason.isSensitiveInfo()) { return res.status(400).json({ error: "The request body contains unexpected sensitive information", }); }
// Block other denials too, such as one from a remote rule. if (decision.isDenied()) { return res.status(403).json({ error: "Forbidden" }); }
// Fail closed when Arcjet couldn't complete the check. if (decision.isErrored()) { return res.status(503).json({ error: "Service unavailable" }); }
res.status(200).json({ name: "Hello world" });}Create a new API route at /pages/api/arcjet.ts:
import arcjet, { sensitiveInfo } from "@arcjet/next";import { rampart } from "@arcjet/sensitive-info-rampart";import type { NextApiRequest, NextApiResponse } from "next";
const aj = arcjet({ key: process.env.ARCJET_KEY!, rules: [ sensitiveInfo({ mode: "LIVE", // Will block requests, use "DRY_RUN" to log only // Detect names and email addresses. See the reference for the full list. deny: ["EMAIL", "GIVEN_NAME", "SURNAME"], // Run detection on-device with the Rampart NER model. backend: rampart(), }), ],});
export default async function handler( req: NextApiRequest, res: NextApiResponse,) { const decision = await aj.protect(req, { sensitiveInfoValue: req.body, }); console.log("Arcjet decision", decision);
if (decision.isDenied() && decision.reason.isSensitiveInfo()) { return res.status(400).json({ error: "The request body contains unexpected sensitive information", }); }
// Block other denials too, such as one from a remote rule. if (decision.isDenied()) { return res.status(403).json({ error: "Forbidden" }); }
// Fail closed when Arcjet couldn't complete the check. if (decision.isErrored()) { return res.status(503).json({ error: "Service unavailable" }); }
res.status(200).json({ name: "Hello world" });}Create a new API route at /app/api/arcjet/route.ts:
import arcjet, { sensitiveInfo } from "@arcjet/next";import { rampart } from "@arcjet/sensitive-info-rampart";import { NextResponse } from "next/server";
// The Rampart backend loads a native ONNX runtime, so this route must run on// the Node.js runtime, not the Edge runtime.export const runtime = "nodejs";
const aj = arcjet({ key: process.env.ARCJET_KEY!, rules: [ sensitiveInfo({ mode: "LIVE", // Will block requests, use "DRY_RUN" to log only // Detect names and email addresses. See the reference for the full list. deny: ["EMAIL", "GIVEN_NAME", "SURNAME"], // Run detection on-device with the Rampart NER model. backend: rampart(), }), ],});
export async function POST(req: Request) { const message = await req.text();
const decision = await aj.protect(req, { sensitiveInfoValue: message, }); console.log("Arcjet decision", decision);
if (decision.isDenied() && decision.reason.isSensitiveInfo()) { return NextResponse.json( { error: "Bad request - sensitive information detected", reason: decision.reason, }, { status: 400, }, ); }
// Block other denials too, such as one from a remote rule. if (decision.isDenied()) { return NextResponse.json({ error: "Forbidden" }, { status: 403 }); }
// Fail closed when Arcjet couldn't complete the check. if (decision.isErrored()) { return NextResponse.json({ error: "Service unavailable" }, { status: 503 }); }
return NextResponse.json({ message: `You said: ${message}` });}Create a new API route at /app/api/arcjet/route.js:
import arcjet, { sensitiveInfo } from "@arcjet/next";import { rampart } from "@arcjet/sensitive-info-rampart";import { NextResponse } from "next/server";
// The Rampart backend loads a native ONNX runtime, so this route must run on// the Node.js runtime, not the Edge runtime.export const runtime = "nodejs";
const aj = arcjet({ key: process.env.ARCJET_KEY, rules: [ sensitiveInfo({ mode: "LIVE", // Will block requests, use "DRY_RUN" to log only // Detect names and email addresses. See the reference for the full list. deny: ["EMAIL", "GIVEN_NAME", "SURNAME"], // Run detection on-device with the Rampart NER model. backend: rampart(), }), ],});
export async function POST(req) { const message = await req.text();
const decision = await aj.protect(req, { sensitiveInfoValue: message, }); console.log("Arcjet decision", decision);
if (decision.isDenied() && decision.reason.isSensitiveInfo()) { return NextResponse.json( { error: "Bad request - sensitive information detected", reason: decision.reason, }, { status: 400, }, ); }
// Block other denials too, such as one from a remote rule. if (decision.isDenied()) { return NextResponse.json({ error: "Forbidden" }, { status: 403 }); }
// Fail closed when Arcjet couldn't complete the check. if (decision.isErrored()) { return NextResponse.json({ error: "Service unavailable" }, { status: 503 }); }
return NextResponse.json({ message: `You said: ${message}` });}The Rampart backend loads a native ONNX runtime, so mark it as a server external
package in next.config.js and keep the route on the Node.js runtime (the App
Router example sets export const runtime = "nodejs"):
/** @type {import('next').NextConfig} */const nextConfig = { serverExternalPackages: [ "@arcjet/sensitive-info-rampart", "@huggingface/transformers", "onnxruntime-node", ],};
module.exports = nextConfig;4. Test sending personal info
Section titled “4. Test sending personal info”Start your app and try making a request with an email address in the body of the request:
curl -v http://localhost:3000/api/arcjet --data "My email address is test@example.com"Your logs show this
Arcjet decision ArcjetDenyDecision { id: '', // This will contain the Arcjet request ID ttl: 0, results: [ ArcjetRuleResult { ruleId: '', ttl: 0, state: 'RUN', conclusion: 'DENY', reason: [ArcjetSensitiveInfoReason] } ],...The default response for a request containing unexpected sensitive information is a 400:
< HTTP/2 400< content-type: application/json; charset=utf-8< date: Tue, 09 Jan 2024 13:43:04 GMT< vary: Accept-Encoding< content-length: 72The requests also appear on the actor’s Activity tab in the Arcjet Console.
Detect PHI with a server-side policy
Section titled “Detect PHI with a server-side policy”The on-device detector in the preceding steps covers personal information such as email addresses. Protected health information (PHI) identifiers, such as medical record numbers and health plan member IDs, often have no fixed format. Arcjet’s server-side detector recognizes them from the label next to the value, and an agent guard policy turns each detection into a decision. Use it to stop AI agents receiving PHI and to stop their tools passing it on.
1. Create a PHI policy
Section titled “1. Create a PHI policy”In the Arcjet Console, go to Policies, click
New policy, choose Your application, and enter note.saved as the
label. Then configure the policy:
| Part | Configuration |
|---|---|
| Input | note, a required String evaluated by Arcjet Cloud |
| Detector | phi, Sensitive information running in Arcjet Cloud over note |
| Deny | MEDICAL_RECORD_NUMBER, HEALTH_PLAN_BENEFICIARY_NUMBER, DEVICE_IDENTIFIER, VEHICLE_IDENTIFICATION_NUMBER, LICENSE_PLATE_NUMBER, and SSN |
| Rule | phi-in-note, Live, decided by A detector directly with phi |
A detector rule needs no Rego and no test. Click Save to publish. A label with no published policy denies nothing. For production traffic, start the rule in Dry run, review what it would deny, and then set it live.
Have your coding agent configure it
Connect the Arcjet MCP server and give your agent this prompt:
Create an Arcjet guard policy with the label note.saved.
Declare note as a required SERVER string. Add a server-side sensitiveinformation detector with the ID phi that reads note and deniesMEDICAL_RECORD_NUMBER, HEALTH_PLAN_BENEFICIARY_NUMBER, DEVICE_IDENTIFIER,VEHICLE_IDENTIFICATION_NUMBER, LICENSE_PLATE_NUMBER, and SSN. Add a liveDETECTOR rule, phi-in-note, decided by phi.
Publish it, then show me the guard() call that sends note.To combine PHI detection with other conditions in Rego, see the PHI example policy.
2. Call the policy
Section titled “2. Call the policy”Where you call the policy decides what it protects, and each call type handles an outage differently:
| Call | Runs | Protects | If Arcjet can’t complete the check |
|---|---|---|---|
Direct guard() | Before the model runs | The model | Fails open: the decision is ALLOW, and hasFailedOpen() is true |
| Wrapped tool | When the agent calls a tool | The tool’s destination | Fails closed: the tool doesn’t run |
A direct call to guard() fails open, so you choose how to handle the flow.
Check for a DENY and for a failed-open decision, and decide what each one
does. For PHI, rejecting the text in both cases keeps the check fail-closed.
A wrapped tool, such as one from guardTool(), fails closed, but you choose
what happens in the flow. Set onGuardError to "allow" to run the tool when
Arcjet can’t complete the check. In most frameworks, onDeny sets what the
model receives when the policy denies the call. Python and Go use the
equivalent on_guard_error, OnGuardError, and OnDeny options.
An agent needs both calls: the direct call keeps PHI out of the model, and the wrapper stops a tool that receives PHI anyway. A web app that sends text to a model needs only the direct call.
Install the Arcjet Guard SDK alongside your framework SDK, for example with npm:
npm i @arcjet/guardCall screenNote() before you store the note or send it to a model:
import { launchArcjet, policyInput } from "@arcjet/guard";
const arcjet = launchArcjet({ key: process.env.ARCJET_KEY! });
// Call this before you store the note or pass it to a model.export async function screenNote(userId: string, note: string) { const decision = await arcjet.guard({ label: "note.saved", actor: userId, // Arcjet's server-side detector reads the note for PHI. inputs: { note: policyInput.server.string(note) }, });
if (decision.conclusion === "DENY") { // The note carries PHI. Ask the user to remove it. throw new Error("Remove health identifiers from the note"); }
if (decision.hasFailedOpen()) { // Arcjet couldn't complete the check, so the call failed open. Reject the // note to fail closed, or log the error and continue to fail open. throw new Error("Couldn't check the note for PHI. Try again."); }}A SERVER input sends the raw note to Arcjet, so sign the BAA before you send
real PHI. For what Arcjet receives and keeps, see
Privacy.
3. Test with PHI
Section titled “3. Test with PHI”Send a note with a labeled medical record number and member ID. Use synthetic values, never real patient records:
Follow-up booked for next week. MRN: 4820193. Member ID: XEH948372615.Arcjet denies the note under phi-in-note. The direct call rejects it before
the model runs, and in an agent, the wrapper stops the tool. For what the detector covers
and its limits, see
Detect protected health information (PHI).
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?”Explore
Section titled “Explore”Arcjet can be used with specific rules on individual routes or as general protection on your entire application. You can set up bot protection, rate limiting for your API, minimize fraudulent registrations with the signup form protection and more.
Get help
Section titled “Get help”Need help with anything? Email support@arcjet.com to get support from our engineering team.