Arcjet Node.js SDK reference
This is the reference guide for the Arcjet Node.js SDK, available on GitHub and licensed under the Apache 2.0 license.
What is Arcjet?
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.Installation
Section titled “Installation”In your project root, install the SDK:
npm i @arcjet/node @arcjet/inspectpnpm add @arcjet/node @arcjet/inspectyarn add @arcjet/node @arcjet/inspectRequirements
Section titled “Requirements”- Node.js 22.21.0 or later
- CommonJS is not supported. Arcjet is ESM only.
Quick start
Section titled “Quick start”See the quick start guide.
Configuration
Section titled “Configuration”Create a new Arcjet object with your API key and rules. Create it outside of
the request handler.
The following fields are required:
key(string) – Your Arcjet site key. This can be found in the SDK Installation section for the site in the Arcjet Dashboard.rules- The rules to apply to the request. See the various sections of the docs for how to configure these, such as shield, rate limiting, bot protection, email validation.
The following fields are optional:
characteristics(string[]) – A list of characteristics to be used to uniquely identify clients.proxies(Array<string | ProxyService>) – A list of one or more trusted proxies. Arcjet excludes these addresses when it determines the client IP address. This is useful if you are behind a load balancer or proxy that sets the client IP address in a header. You can also pass a proxy service such ascloudflare()to read the real client IP from a service-specific header. For an example, see Load balancers and proxies.
import arcjet, { shield } from "@arcjet/node";
const aj = arcjet({ // Get your site key from https://app.arcjet.com // and set it as an environment variable rather than hard coding. // See: https://www.npmjs.com/package/dotenv key: process.env.ARCJET_KEY!, rules: [ // Protect against common attacks with Arcjet Shield shield({ mode: "LIVE", // will block requests. Use "DRY_RUN" to log only }), ],});import arcjet, { shield } from "@arcjet/node";
const aj = arcjet({ // Get your site key from https://app.arcjet.com // and set it as an environment variable rather than hard coding. // See: https://www.npmjs.com/package/dotenv key: process.env.ARCJET_KEY, rules: [ // Protect against common attacks with Arcjet Shield shield({ mode: "LIVE", // will block requests. Use "DRY_RUN" to log only }), ],});Single instance
Section titled “Single instance”We recommend creating a single instance of the Arcjet object and reusing it
throughout your application. This is because the SDK caches decisions and
configuration to improve performance.
The pattern we use is to create a utility file that exports the Arcjet object
and then import it where you need it.
Rule modes
Section titled “Rule modes”Each rule can be configured in either LIVE or DRY_RUN mode. When in
DRY_RUN mode, each rule returns its decision, but the end conclusion is always
ALLOW.
This lets you run Arcjet in passive or demo mode to test rules before enabling them.
Because the top level conclusion is always ALLOW in DRY_RUN mode, you can
loop through each rule result to check what would have happened:
for (const result of decision.results) { if (result.isDenied()) { console.log("Rule returned deny conclusion", result); }}Multiple rules
Section titled “Multiple rules”You can combine rules to create a more complex protection strategy. For example, you can combine rate limiting and bot protection rules to protect your API from automated clients.
import arcjet, { detectBot, tokenBucket } from "@arcjet/node";
// Create an Arcjet instance with multiple rulesconst aj = arcjet({ key: process.env.ARCJET_KEY!, // Get your site key from https://app.arcjet.com rules: [ tokenBucket({ mode: "LIVE", // will block requests. Use "DRY_RUN" to log only refillRate: 5, // refill 5 tokens per interval interval: 10, // refill every 10 seconds capacity: 10, // bucket maximum capacity of 10 tokens }), detectBot({ mode: "LIVE", allow: [], // "allow none" will block all detected bots }), ],});import arcjet, { detectBot, tokenBucket } from "@arcjet/node";
// Create an Arcjet instance with multiple rulesconst aj = arcjet({ key: process.env.ARCJET_KEY, // Get your site key from https://app.arcjet.com rules: [ tokenBucket({ mode: "LIVE", // will block requests. Use "DRY_RUN" to log only refillRate: 5, // refill 5 tokens per interval interval: 10, // refill every 10 seconds capacity: 10, // bucket maximum capacity of 10 tokens }), detectBot({ mode: "LIVE", allow: [], // "allow none" will block all detected bots }), ],});Environment variables
Section titled “Environment variables”The Arcjet Node.js SDK uses several environment variables to configure its
behavior. For more information, see Concepts: Environment variables. The ARCJET_KEY environment variable
is not read automatically and must be passed explicitly.
Custom logging
Section titled “Custom logging”The SDK uses a lightweight logger which mirrors the Pino structured logger interface. You can use this to customize the logging output.
First, install the required packages:
npm install pino pino-prettyThen, create a custom logger that logs to JSON in production and pretty prints in development:
import arcjet, { shield } from "@arcjet/node";import pino, { type Logger } from "pino";
const logger: Logger = process.env.ARCJET_ENV !== "development" ? // JSON in production, default to warn pino({ level: process.env.ARCJET_LOG_LEVEL || "warn" }) : // Pretty print in development, default to debug pino({ transport: { target: "pino-pretty", options: { colorize: true, }, }, level: process.env.ARCJET_LOG_LEVEL || "debug", });
const aj = arcjet({ key: process.env.ARCJET_KEY!, rules: [ // Protect against common attacks with Arcjet Shield shield({ mode: "LIVE", // will block requests. Use "DRY_RUN" to log only }), ], // Use the custom logger log: logger,});import arcjet, { shield } from "@arcjet/node";import pino from "pino";
const logger = process.env.ARCJET_ENV !== "development" ? // JSON in production, default to warn pino({ level: process.env.ARCJET_LOG_LEVEL || "warn" }) : // Pretty print in development, default to debug pino({ transport: { target: "pino-pretty", options: { colorize: true, }, }, level: process.env.ARCJET_LOG_LEVEL || "debug", });
const aj = arcjet({ key: process.env.ARCJET_KEY, rules: [ // Protect against common attacks with Arcjet Shield shield({ mode: "LIVE", // will block requests. Use "DRY_RUN" to log only }), ], // Use the custom logger log: logger,});Load balancers and proxies
Section titled “Load balancers and proxies”If your application is behind a load balancer, Arcjet sees only the IP address of the load balancer and not the real client IP address.
To fix this, most load balancers set the X-Forwarded-For header with the real
client IP address plus a list of proxies that the request has passed through.
The problem is that the client can spoof the X-Forwarded-For header, so trust
it only if you are sure the load balancer sets it correctly. For more
information, see the MDN documentation for
X-Forwarded-For.
You can configure Arcjet to trust IP addresses in the X-Forwarded-For header
by setting the proxies field in the configuration. Set this to a list of the
IP addresses or CIDR ranges of your load balancers to remove, so the last IP
address in the list is the real client IP address.
Example
Section titled “Example”For example, if the load balancer is at 203.0.113.100 and the client IP
address is 198.51.100.1, the X-Forwarded-For header is:
X-Forwarded-For: 198.51.100.1, 203.0.113.100Set the proxies field to ["203.0.113.100"] so Arcjet uses 198.51.100.1 as
the client IP address.
You can also specify CIDR ranges to match multiple IP addresses.
import arcjet from "@arcjet/node";
const aj = arcjet({ key: process.env.ARCJET_KEY!, rules: [], proxies: [ "203.0.113.100", // A single IP "203.0.113.0/24", // A CIDR for the range ],});Proxy services
Section titled “Proxy services”Some providers pass the real client IP in their own header rather than adding
themselves to X-Forwarded-For. For these you can pass a proxy service in the
proxies list. The cloudflare() helper reads the real client IP from
Cloudflare’s CF-Connecting-IP header when the request comes from a Cloudflare
IP range:
import arcjet, { cloudflare } from "@arcjet/node";
const aj = arcjet({ key: process.env.ARCJET_KEY!, rules: [], // Read the real client IP from Cloudflare's `CF-Connecting-IP` header when // the request arrives from a Cloudflare IP range proxies: [cloudflare()],});See the best practices guide for more, including running Cloudflare in front of your app and handling a Cloudflare range the SDK doesn’t know about yet.
Protect
Section titled “Protect”Arcjet provides a single protect function that is used to execute your
protection rules. This requires a request object, which you must construct
with your incoming request. Rules you add to the SDK may require additional
details, such as the validateEmail rule requiring an additional email prop.
This function returns a Promise that resolves to an ArcjetDecision object,
which provides a high-level conclusion and detailed explanations of the decision
made by Arcjet.
import arcjet, { tokenBucket } 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: [ // Create a token bucket rate limit. Other algorithms are supported. tokenBucket({ mode: "LIVE", // will block requests. Use "DRY_RUN" to log only characteristics: ["userId"], // track requests by a custom user ID refillRate: 5, // refill 5 tokens per interval interval: 10, // refill every 10 seconds capacity: 10, // bucket maximum capacity of 10 tokens }), ],});
const server = http.createServer(async function ( req: http.IncomingMessage, res: http.ServerResponse,) { const userId = "user123"; // Replace with your authenticated user ID // The userId prop is required because it is defined in the characteristics // prop of the tokenBucket rule. const decision = await aj.protect(req, { userId, requested: 5 }); // Deduct 5 tokens from the bucket console.log("Arcjet decision", decision);
if (decision.isDenied()) { res.writeHead(429, { "Content-Type": "application/json" }); res.end( JSON.stringify({ error: "Too Many Requests", reason: decision.reason }), ); } else { res.writeHead(200, { "Content-Type": "application/json" }); res.end(JSON.stringify({ message: "Hello world" })); }});
server.listen(8000);import arcjet, { tokenBucket } 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: [ // Create a token bucket rate limit. Other algorithms are supported. tokenBucket({ mode: "LIVE", // will block requests. Use "DRY_RUN" to log only characteristics: ["userId"], // track requests by a custom user ID refillRate: 5, // refill 5 tokens per interval interval: 10, // refill every 10 seconds capacity: 10, // bucket maximum capacity of 10 tokens }), ],});
const server = http.createServer(async function (req, res) { const userId = "user123"; // Replace with your authenticated user ID // The userId prop is required because it is defined in the characteristics // prop of the tokenBucket rule. const decision = await aj.protect(req, { userId, requested: 5 }); // Deduct 5 tokens from the bucket console.log("Arcjet decision", decision);
if (decision.isDenied()) { res.writeHead(429, { "Content-Type": "application/json" }); res.end( JSON.stringify({ error: "Too Many Requests", reason: decision.reason }), ); } else { res.writeHead(200, { "Content-Type": "application/json" }); res.end(JSON.stringify({ message: "Hello world" })); }});
server.listen(8000);Override the client IP
Section titled “Override the client IP”Arcjet normally detects the client IP address from the request. If your
application has already determined the client IP from a trusted source, pass it
as ipSrc in the second argument to protect(). In this example,
requestInput represents the request or framework context normally passed to
protect():
const ipSrc = getClientIpFromTrustedSource(requestInput);const decision = await aj.protect(requestInput, { ipSrc });A non-empty ipSrc takes precedence over automatic detection, including the
development-only x-arcjet-ip header. If ipSrc is an empty string, Arcjet
uses automatic detection instead.
Caution: The SDK trusts
ipSrcwithout validating it. Validate the value and ensure it comes from a trusted source. Do not pass a client-controlled header directly; doing so could allow clients to choose the IP address used for fingerprinting, rate limiting, and other security checks.
Metadata
Section titled “Metadata”protect() accepts metadata: an object of string keys mapped to any
JSON-serializable value, including nested objects, arrays, numbers, booleans,
and null. It is attached to the decision for correlation and analytics and
does not affect the decision or its cache key.
const decision = await aj.protect(requestInput, { metadata: { requestId, user: { id: userId, plan: "pro" }, flags: { beta: true }, },});Each top-level value is JSON-encoded by the SDK. Keys the SDK cannot encode
(undefined, a function, a BigInt, a circular reference) are dropped with a
single AJ1017 warning naming them. A metadata that is not a plain object is
ignored entirely. Prefer metadata over extra, which stays a flat string map.
Metadata is untrusted and is not redacted – do not put secrets or PII in it.
JavaScript numbers are IEEE-754 doubles, so pass an integer above
Number.MAX_SAFE_INTEGER as a string.
For limits, drop behavior, and language-specific notes, see Guard metadata.
Decision
Section titled “Decision”The protect function 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("ALLOW" | "DENY" | "CHALLENGE" | "ERROR") – 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 ofArcjetRuleResultobjects containing the results of each rule that was executed.ttl(uint32) – The time-to-live for the decision in seconds. This is the time that the decision is valid for. After this time, Arcjet re-evaluates the decision. The SDK automatically cachesDENYdecisions for the length of the TTL.ip(ArcjetIpDetails) – An object containing Arcjet’s analysis of the client IP address. For more information, see IP analysis.
Conclusion
Section titled “Conclusion”Use the following ArcjetDecision methods to check the conclusion:
isAllowed()(bool) – Arcjet concluded that the request is allowed.isDenied()(bool) – Arcjet concluded that the request is denied.isErrored()(bool) – There was an unrecoverable error.
The conclusion is the highest-severity finding from the configured rules.
"DENY" is the highest severity, followed by "CHALLENGE", then "ERROR" and
finally "ALLOW" as the lowest severity.
For example, when a bot protection rule returns an error and a validate email
rule returns a deny, the overall conclusion would be deny. To access the error
you would have to use the results property on the decision.
Reason
Section titled “Reason”The reason property of the ArcjetDecision object contains an ArcjetReason
object which provides more detailed information about the conclusion. This is
the final decision reason and is based on the configured rules.
It is always the highest-priority rule that produced that conclusion; to inspect
other rules, iterate over the results property on the decision.
The ArcjetReason object has the following methods that can be used to check
which rule caused the conclusion:
isBot()(bool) – Returnstrueif the bot protection rules have been applied and the request was considered to have been made by a bot.isEmail()(bool) – Returnstrueif the email rules have been applied and the email address has a problem.isRateLimit()(bool) – Returnstrueif the rate limit rules have been applied and the request has exceeded the rate limit.isSensitiveInfo()(bool) – Returnstrueif sensitive info rules have been applied and sensitive info has been detected.isPromptInjection()(bool) – Returnstrueif the prompt injection rules have been applied and a prompt injection attempt was detected.isShield()(bool) – Returnstrueif the shield rules have been applied and the request is suspicious based on analysis by Arcjet Shield WAF.isError()(bool) – Returnstrueif there was an error processing the request.
Results
Section titled “Results”The results property of the ArcjetDecision object contains an array of
ArcjetRuleResult objects. There is one for each configured rule, so you can
inspect the individual results:
id(string) – The ID of the rule result. Not yet implemented.state(ArcjetRuleState) – Whether the rule was executed or not.conclusion(ArcjetConclusion) – The conclusion of the rule. This is one of the preceding conclusions:ALLOW,DENY,CHALLENGE, orERROR.reason(ArcjetReason) – An object containing more detailed information about the conclusion for this rule. Each rule type has its own reason object with different properties.
You can iterate through the results and check the conclusion for each rule.
for (const result of decision.results) { console.log("Rule Result", result);}Rule state
Section titled “Rule state”The state property of the ArcjetRuleResult object is an ArcjetRuleState.
Each rule is evaluated individually and can be in one of the following states:
DRY_RUN- The rule was executed in dry run mode. This means that the rule was executed but the conclusion was not applied to the request. This is useful for testing rules before enabling them.RUN- The rule was executed and the conclusion was applied to the request.NOT_RUN- The rule was not executed. This can happen if another rule has already reached a conclusion that applies to the request. For example, if a rate limit rule is configured then these are evaluated before all other rules. If the client has reached the maximum number of requests then Arcjet doesn’t evaluate the other rules.CACHED- The rule was not executed because the previous result was cached. Results are cached when the decision conclusion isDENY. Arcjet doesn’t evaluate subsequent requests from the same client against the rule until the cache expires.
Rule reason
Section titled “Rule reason”The reason property of the ArcjetRuleResult object contains an
ArcjetReason object which provides more detailed information about the
conclusion for that configured rule.
Shield
Section titled “Shield”The ArcjetReason object for shield rules has the following properties:
shieldTriggered: boolean;For more information about these properties, see the shield documentation.
Bot protection
Section titled “Bot protection”The ArcjetReason object for bot protection rules has the following properties:
allowed: string[];denied: string[];Each of the allowed and denied arrays contains the identifiers of the bots
allowed or denied from our full list of bots.
Rate limiting
Section titled “Rate limiting”The ArcjetReason object for rate limiting rules has the following properties:
max: number;remaining: number;window: number;reset: number;For more information about these properties, see the rate limiting documentation.
Email validation and verification
Section titled “Email validation and verification”The ArcjetReason object for email rules has the following properties:
emailTypes: ArcjetEmailType[];An ArcjetEmailType is one of the following strings:
"DISPOSABLE" | "FREE" | "NO_MX_RECORDS" | "NO_GRAVATAR" | "INVALID";For more information about these properties, see the email validation documentation.
Prompt injection
Section titled “Prompt injection”The ArcjetReason object for prompt injection rules has the following
properties:
injectionDetected: boolean;injectionDetected is true when the detector found a prompt injection
attempt. You can also call reason.isPromptInjection(). For more
information about these properties, see the
prompt injection documentation.
IP analysis
Section titled “IP analysis”The ArcjetDecision object contains an ip
property. This includes additional data about the client IP address:
IP location
country(string | undefined): the country code the client IP address.countryName(string | undefined): the country name of the client IP address.latitude(number | undefined): the latitude of the client IP address.longitude(number | undefined): the longitude of the client IP address.accuracyRadius(number | undefined): how accurate the location is in kilometers.timezone(string | undefined): the timezone of the client IP address.postalCode(string | undefined): the postal or zip code of the client IP address.city(string | undefined): the city of the client IP address.region(string | undefined): the region of the client IP address.continent(string | undefined): the continent code of the client IP address.continentName(string | undefined): the continent name of the client IP address.
The IP location fields may be undefined, but you can use various methods to
check their availability. These methods also refine the type, which removes the
need for null or undefined checks.
hasLatitude()(bool): returns whether thelatitudeandaccuracyRadiusfields are available.hasLongitude()(bool): returns whether thelongitudeandaccuracyRadiusfields are available.hasAccuracyRadius()(bool): returns whether thelongitude,latitude, andaccuracyRadiusfields are available.hasTimezone()(bool): returns whether thetimezonefield is available.hasPostalCode()(bool): returns whether thepostalCodefield is available.hasCity()(bool): returns whether thecityfield is available.hasRegion()(bool): returns whether theregionfield is available.hasCountry()(bool): returns whether thecountryandcountryNamefields are available.hasContinent()(bool): returns whether thecontinentandcontinentNamefields are available.
Location accuracy
IP geolocation can be notoriously inaccurate, especially for mobile devices,
satellite internet providers, and even ordinary users. Likewise with the
specific fields like city and region, which can be very inaccurate. Country
is usually accurate, but there are often cases where IP addresses are
mislocated. These fields are provided for convenience, such as suggesting a user
location, but don’t rely on them alone.
IP autonomous system
This is useful for identifying the network operator of the client IP address. This is useful for understanding whether the client is likely to be automated or not, or being stricter with requests from certain networks.
The IP AS fields may be undefined, but you can use the hasASN() method to
check their availability. This method also refines the type, which removes the
need for null-ish checks.
hasASN()(bool): returns whether all of the ASN fields are available.asn(string | undefined): the autonomous system (AS) number of the client IP address.asnName(string | undefined): the name of the AS of the client IP address.asnDomain(string | undefined): the domain of the AS of the client IP address.asnType('isp' | 'hosting' | 'business' | 'education'): the type of the AS of the client IP address. Real users are more likely to be on an ISP or business network rather than a hosting provider. Education networks often have a single or small number of IP addresses even though there are many users. A common mistake is to block a single IP because of too many requests when it is a university or company network using NAT (Network Address Translation) to give many users the same IP.asnCountry(string | undefined): the country code of the AS of the client IP address. This is the administrative country of the AS, not necessarily the country of the client IP address.
IP threat intelligence
When threat intelligence is available, it is exposed as decision.ip.threat.
Always check for it because older responses and IPs without an assessment omit
the property:
const threat = decision.ip.threat;
if (threat && !threat.isSafe && threat.riskLevel === "critical") { console.warn("High-risk IP activity", threat.activities);}riskLevel(string): overall risk assessment, such asnone,low,medium,high, orcritical.confidence(string): confidence in the assessment, such aslow,medium, orhigh.reputation(string): upstream reputation, such asmalicious,suspicious,known,safe,benign, orunknown.isSafe(boolean): whether the IP is trusted infrastructure rather than a threat.networkTypes(string[]): network classifications, such ashosting,vpn,proxy, ortor.activities(string[]): observed behaviors, such asbrute_force,scanning, orbotnet.entities(string[]): automated entity types, such ascrawler,ai_crawler, orscanner.entityName(string | undefined): a specific entity name, when identified.service(string | undefined): a known service or provider name, when identified.
IP type
The service field may be undefined, but you can use the hasService()
method to check the availability. This method also refines the type, which
removes the need for null-ish checks.
The following are available on all pricing plans:
hasService()(bool): whether theservicefield is available.service(string | undefined): the name of the service associated with the IP address, such asApple Private Relay.isHosting()(bool): returns whether the IP address of the client is owned by a hosting provider. Requests originating from a hosting provider IP significantly increase the likelihood that this is an automated client.isVpn()(bool): returns whether the IP address of the client is owned by a VPN provider. Many people use VPNs for privacy or work purposes, so by itself this is not an indicator of the client being automated. However, it does increase the risk score of the client and depending on your use case it may be a characteristic you wish to restrict.isProxy()(bool): returns whether the IP address of the client is owned by a proxy provider. Similar toisVpn(), but proxies are more likely to involve automated traffic.isTor()(bool): returns whether the IP address of the client is known to be part of the Tor network. As withisVpn(), there are legitimate uses for hiding your identity through Tor, however it is also often a way to hide the origin of malicious traffic.isRelay()(bool): returns whether the IP address of the client is owned by a relay service. The most common example is Apple iCloud Relay, which indicates the client is less likely to be automated because Apple requires a paid subscription linked to an Apple account in good standing.
Example
Section titled “Example”import arcjet, { shield } 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: [ shield({ mode: "LIVE", // will block requests. Use "DRY_RUN" to log only }), ],});
const server = http.createServer(async function ( req: http.IncomingMessage, res: http.ServerResponse,) { const decision = await aj.protect(req);
if (decision.isDenied()) { res.writeHead(403, { "Content-Type": "application/json" }); res.end(JSON.stringify({ error: "Forbidden", reason: decision.reason })); return; }
if (decision.ip.hasCountry()) { res.writeHead(200, { "Content-Type": "application/json" }); res.end( JSON.stringify({ message: `Hello ${decision.ip.countryName}!`, country: decision.ip, }), ); } else { res.writeHead(200, { "Content-Type": "application/json" }); res.end(JSON.stringify({ message: "Hello world" })); }});
server.listen(8000);import arcjet, { shield } 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: [ shield({ mode: "LIVE", // will block requests. Use "DRY_RUN" to log only }), ],});
const server = http.createServer(async function (req, res) { const decision = await aj.protect(req);
if (decision.isDenied()) { res.writeHead(403, { "Content-Type": "application/json" }); res.end(JSON.stringify({ error: "Forbidden", reason: decision.reason })); return; }
if (decision.ip.hasCountry()) { res.writeHead(200, { "Content-Type": "application/json" }); res.end( JSON.stringify({ message: `Hello ${decision.ip.countryName}!`, country: decision.ip, }), ); } else { res.writeHead(200, { "Content-Type": "application/json" }); res.end(JSON.stringify({ message: "Hello world" })); }});
server.listen(8000);For the IP address 8.8.8.8 you might get the following response. Arcjet
returns only the fields it has data for:
{ "name": "Hello United States!", "ip": { "country": "US", "countryName": "United States", "continent": "NA", "continentName": "North America", "asn": "AS15169", "asnName": "Google LLC", "asnDomain": "google.com" }}Error handling
Section titled “Error handling”Arcjet is designed to fail open so that a service issue or misconfiguration does not block all requests. The SDK also times out and fails open after 2000 ms by default. However, in most cases, the response time is less than 20 ms to 30 ms.
If there is an error condition when processing the rule, Arcjet returns 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 is ERROR.
import arcjet, { slidingWindow } from "@arcjet/node";import http from "node:http";
const aj = arcjet({ key: process.env.ARCJET_KEY!, rules: [ slidingWindow({ mode: "LIVE", interval: "1h", max: 60, }), ],});
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.isError()) { // 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" })); //return; } }
if (decision.isDenied()) { res.writeHead(403, { "Content-Type": "application/json" }); res.end(JSON.stringify({ error: "Forbidden" })); return; }
res.writeHead(200, { "Content-Type": "application/json" }); res.end(JSON.stringify({ message: "Hello world" }));});
server.listen(8000);import arcjet, { slidingWindow } from "@arcjet/node";import http from "node:http";
const aj = arcjet({ key: process.env.ARCJET_KEY, rules: [ slidingWindow({ mode: "LIVE", interval: "1h", max: 60, }), ],});
const server = http.createServer(async function (req, res) { const decision = await aj.protect(req);
for (const { reason } of decision.results) { if (reason.isError()) { // 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" })); //return; } }
if (decision.isDenied()) { res.writeHead(403, { "Content-Type": "application/json" }); res.end(JSON.stringify({ error: "Forbidden" })); return; }
res.writeHead(200, { "Content-Type": "application/json" }); res.end(JSON.stringify({ message: "Hello world" }));});
server.listen(8000);The @arcjet/inspect package provides utilities for dealing with common errors.
import arcjet, { detectBot } from "@arcjet/node";import { isMissingUserAgent } from "@arcjet/inspect";import http from "node:http";
const aj = arcjet({ key: process.env.ARCJET_KEY!, rules: [ detectBot({ mode: "LIVE", allow: [], }), ],});
const server = http.createServer(async function ( req: http.IncomingMessage, res: http.ServerResponse,) { const decision = await aj.protect(req);
if (decision.isDenied()) { res.writeHead(403, { "Content-Type": "application/json" }); res.end(JSON.stringify({ error: "Forbidden" })); return; }
if (decision.results.some(isMissingUserAgent)) { // Requests without User-Agent headers might not be identified as any // particular bot and could be marked as an errored result. Most legitimate // clients send this header, so we recommend blocking requests without it. // See https://docs.arcjet.com/bot-protection/reference#user-agent-header console.warn("User-Agent header is missing");
res.writeHead(400, { "Content-Type": "application/json" }); res.end(JSON.stringify({ error: "Bad request" })); return; }
res.writeHead(200, { "Content-Type": "application/json" }); res.end(JSON.stringify({ message: "Hello world" }));});
server.listen(8000);import arcjet, { detectBot } from "@arcjet/node";import { isMissingUserAgent } from "@arcjet/inspect";import http from "node:http";
const aj = arcjet({ key: process.env.ARCJET_KEY, rules: [ detectBot({ mode: "LIVE", allow: [], }), ],});
const server = http.createServer(async function (req, res) { const decision = await aj.protect(req);
if (decision.isDenied()) { res.writeHead(403, { "Content-Type": "application/json" }); res.end(JSON.stringify({ error: "Forbidden" })); return; }
if (decision.results.some(isMissingUserAgent)) { // Requests without User-Agent headers might not be identified as any // particular bot and could be marked as an errored result. Most legitimate // clients send this header, so we recommend blocking requests without it. // See https://docs.arcjet.com/bot-protection/reference#user-agent-header console.warn("User-Agent header is missing");
res.writeHead(400, { "Content-Type": "application/json" }); res.end(JSON.stringify({ error: "Bad request" })); return; }
res.writeHead(200, { "Content-Type": "application/json" }); res.end(JSON.stringify({ message: "Hello world" }));});
server.listen(8000);Ad hoc rules
Section titled “Ad hoc rules”Sometimes it is useful to add extra protection with a rule based on the logic in
your handler; however, you usually want to inherit the rules, cache, and other
configuration from our primary SDK. This can be achieved using the withRule
function which accepts an ad-hoc rule and can be chained to add multiple rules.
It returns an augmented client with the specialized protect function.
import arcjet, { detectBot, fixedWindow, shield } 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: [ // Protect against common attacks with Arcjet Shield shield({ mode: "LIVE", // will block requests. Use "DRY_RUN" to log only }), ],});
function getClient(userId?: string) { if (userId) { return aj; } else { // Only apply bot detection and rate limiting to non-authenticated users return ( aj .withRule( fixedWindow({ max: 10, window: "1m", }), ) // You can chain multiple rules, or just use one .withRule( 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,) { // This userId is hard coded for the example, but this is where you would do a // session lookup and get the user ID. const userId = "totoro";
const decision = await getClient(userId).protect(req);
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 }), ); } else { res.writeHead(403, { "Content-Type": "application/json" }); res.end(JSON.stringify({ error: "Forbidden", reason: decision.reason })); } } else { res.writeHead(200, { "Content-Type": "application/json" }); res.end(JSON.stringify({ message: "Hello world" })); }});
server.listen(8000);import arcjet, { detectBot, fixedWindow, shield } 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: [ // Protect against common attacks with Arcjet Shield shield({ mode: "LIVE", // will block requests. Use "DRY_RUN" to log only }), ],});
function getClient(userId) { if (userId) { return aj; } else { // Only apply bot detection and rate limiting to non-authenticated users return ( aj .withRule( fixedWindow({ max: 10, window: "1m", }), ) // You can chain multiple rules, or just use one .withRule( 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) { // This userId is hard coded for the example, but this is where you would do a // session lookup and get the user ID. const userId = "totoro";
const decision = await getClient(userId).protect(req);
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 }), ); } else { res.writeHead(403, { "Content-Type": "application/json" }); res.end(JSON.stringify({ error: "Forbidden", reason: decision.reason })); } } else { res.writeHead(200, { "Content-Type": "application/json" }); res.end(JSON.stringify({ message: "Hello world" })); }});
server.listen(8000);IP address detection
Section titled “IP address detection”Arcjet automatically detects the IP address of the client making the request based on the context provided. The implementation is open source in our @arcjet/ip package.
in development (see
ARCJET_ENV), we allow
private/internal addresses so that the SDKs work correctly locally.
Client override
Section titled “Client override”You can override the default client. If you don’t specify a client, Arcjet uses a default one. You don’t usually need to provide a client – the Arcjet SDK handles this for you.
import arcjet, { createRemoteClient, slidingWindow } from "@arcjet/node";import { baseUrl } from "@arcjet/env";
const client = createRemoteClient({ // baseUrl defaults to https://decide.arcjet.com and should only be changed if // directed by Arcjet. // It can also be set using the // [`ARCJET_BASE_URL`](https://docs.arcjet.com/environment#arcjet-base-url) // environment variable. baseUrl: baseUrl(process.env), // timeout is the maximum time to wait for a response from the server. // It defaults to 2000ms. This is a conservative limit to fail open by default. // In most cases, the response time will be <20-30ms. timeout: 2000,});
const aj = arcjet({ key: process.env.ARCJET_KEY!, rules: [ slidingWindow({ mode: "LIVE", interval: "1h", max: 60, }), ], client,});import arcjet, { createRemoteClient, slidingWindow } from "@arcjet/node";import { baseUrl } from "@arcjet/env";
const client = createRemoteClient({ // baseUrl defaults to https://decide.arcjet.com and should only be changed if // directed by Arcjet. // It can also be set using the // [`ARCJET_BASE_URL`](https://docs.arcjet.com/environment#arcjet-base-url) // environment variable. baseUrl: baseUrl(process.env), // timeout is the maximum time to wait for a response from the server. // It defaults to 2000ms. This is a conservative limit to fail open by default. // In most cases, the response time will be <20-30ms. timeout: 2000,});
const aj = arcjet({ key: process.env.ARCJET_KEY, rules: [ slidingWindow({ mode: "LIVE", interval: "1h", max: 60, }), ], client,});Version support
Section titled “Version support”Arcjet supports the active and maintenance LTS versions of Node.js 22.21.0 or later.
When a Node.js version goes end of life, we bump the major version of the Arcjet SDK. Technical support is provided for the current major version of the Arcjet SDK for all users and for the current and previous major versions for paid users. We provide security fixes for the current and previous major SDK versions.