Signup from protection reference
Arcjet signup form protection combines rate limiting, bot protection, and email validation to protect your signup forms from abuse.
Plan availability
Arcjet signup form protection availability depends depends on your pricing plan.
Plan | Signup form protection |
---|---|
Free | No |
Pro | Yes |
Enterprise | Custom |
Configuration
Signup form protection is a combination of the rate limiting, bot protection, and email validation primitives. The configuration options are the same, but specified in a single rule.
The configuration definition is:
type ProtectSignupOptions = { rateLimit?: SlidingWindowRateLimitOptions | SlidingWindowRateLimitOptions[]; bots?: | BotOptionsAllow | BotOptionsDeny | BotOptionsAllow[] | BotOptionsDeny[]; email?: EmailOptions | EmailOptions[];};
The arcjet
client is configured with one protectSignup
rule which take
ProtectSignupOptions
.
Recommended configuration
Our recommended configuration for most signup forms is:
- Block emails with invalid syntax, that are from disposable email providers, or do not have valid MX records configured.
- Block clients that we are sure are automated.
- Apply a rate limit of 5 submissions per 10 minutes from a single IP address.
This can be configured as follows:
import { protectSignup } from "@arcjet/nest";
protectSignup({ email: { mode: "LIVE", // will block requests. Use "DRY_RUN" to log only // Block emails that are disposable, invalid, or have no MX records block: ["DISPOSABLE", "INVALID", "NO_MX_RECORDS"], }, bots: { mode: "LIVE", // configured with a list of bots to allow from // https://arcjet.com/bot-list allow: [], // "allow none" will block all detected bots }, // It would be unusual for a form to be submitted more than 5 times in 10 // minutes from the same IP address rateLimit: { // uses a sliding window rate limit mode: "LIVE", interval: "10m", // counts requests over a 10 minute sliding window max: 5, // allows 5 submissions within the window },});
import arcjet, { protectSignup } from "@arcjet/bun";import { env } from "bun";
const aj = arcjet({ key: env.ARCJET_KEY!, // Get your site key from https://app.arcjet.com rules: [ protectSignup({ email: { mode: "LIVE", // will block requests. Use "DRY_RUN" to log only // Block emails that are disposable, invalid, or have no MX records block: ["DISPOSABLE", "INVALID", "NO_MX_RECORDS"], }, bots: { mode: "LIVE", // configured with a list of bots to allow from // https://arcjet.com/bot-list allow: [], // "allow none" will block all detected bots }, // It would be unusual for a form to be submitted more than 5 times in 10 // minutes from the same IP address rateLimit: { // uses a sliding window rate limit mode: "LIVE", interval: "10m", // counts requests over a 10 minute sliding window max: 5, // allows 5 submissions within the window }, }), ],});
import arcjet, { protectSignup } from "@arcjet/next";
const aj = arcjet({ key: process.env.ARCJET_KEY!, rules: [ protectSignup({ email: { mode: "LIVE", // will block requests. Use "DRY_RUN" to log only // Block emails that are disposable, invalid, or have no MX records block: ["DISPOSABLE", "INVALID", "NO_MX_RECORDS"], }, bots: { mode: "LIVE", // configured with a list of bots to allow from // https://arcjet.com/bot-list allow: [], // "allow none" will block all detected bots }, // It would be unusual for a form to be submitted more than 5 times in 10 // minutes from the same IP address rateLimit: { // uses a sliding window rate limit mode: "LIVE", interval: "10m", // counts requests over a 10 minute sliding window max: 5, // allows 5 submissions within the window }, }), ],});
import arcjet, { protectSignup } from "@arcjet/node";
const aj = arcjet({ key: process.env.ARCJET_KEY!, rules: [ protectSignup({ email: { mode: "LIVE", // will block requests. Use "DRY_RUN" to log only // Block emails that are disposable, invalid, or have no MX records block: ["DISPOSABLE", "INVALID", "NO_MX_RECORDS"], }, bots: { mode: "LIVE", // configured with a list of bots to allow from // https://arcjet.com/bot-list allow: [], // "allow none" will block all detected bots }, // It would be unusual for a form to be submitted more than 5 times in 10 // minutes from the same IP address rateLimit: { // uses a sliding window rate limit mode: "LIVE", interval: "10m", // counts requests over a 10 minute sliding window max: 5, // allows 5 submissions within the window }, }), ],});
import arcjet, { protectSignup } from "@arcjet/remix";
const aj = arcjet({ key: process.env.ARCJET_KEY!, rules: [ protectSignup({ email: { mode: "LIVE", // will block requests. Use "DRY_RUN" to log only // Block emails that are disposable, invalid, or have no MX records block: ["DISPOSABLE", "INVALID", "NO_MX_RECORDS"], }, bots: { mode: "LIVE", // configured with a list of bots to allow from // https://arcjet.com/bot-list allow: [], // "allow none" will block all detected bots }, // It would be unusual for a form to be submitted more than 5 times in 10 // minutes from the same IP address rateLimit: { // uses a sliding window rate limit mode: "LIVE", interval: "10m", // counts requests over a 10 minute sliding window max: 5, // allows 5 submissions within the window }, }), ],});
import { env } from "$env/dynamic/private";import arcjet, { protectSignup } from "@arcjet/sveltekit";
const aj = arcjet({ key: env.ARCJET_KEY!, rules: [ protectSignup({ email: { mode: "LIVE", // will block requests. Use "DRY_RUN" to log only // Block emails that are disposable, invalid, or have no MX records block: ["DISPOSABLE", "INVALID", "NO_MX_RECORDS"], }, bots: { mode: "LIVE", // configured with a list of bots to allow from // https://arcjet.com/bot-list allow: [], // "allow none" will block all detected bots }, // It would be unusual for a form to be submitted more than 5 times in 10 // minutes from the same IP address rateLimit: { // uses a sliding window rate limit mode: "LIVE", interval: "10m", // counts requests over a 10 minute sliding window max: 5, // allows 5 submissions within the window }, }), ],});
Testing with dry run mode
When you are testing your signup form protection configuration, you can run the
rules in dry run mode first by setting mode
to DRY_RUN
. This will return an
allow decision for every request, but log what the results would have been if
they were in live mode. You can view the results in the Arcjet
dashboard.
Even in dry run mode each rule will still be evaluated, so you can still check the rule results to see if the email address is valid or not, or log them to your database.
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
Arcjet 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. When configured with a protectSignup
rule it also requires an additional email
prop.
Arcjet can be integrated using a global guard
or per route guards. However these can’t be used for signup protection rules
because you can’t access the decision to handle the form submission. Instead,
you call the protect
function in your route handler. See
bot protection for an example where guards are
used.
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.
Accepting our recommended action
The conclusion
property contains the final conclusion based on evaluating each
of the configured rules. The quick start example code above uses this property
to accept Arcjet’s recommended action - display an error to the user if their
email is rejected, otherwise return a 403
error.
You can check if a deny decision was returned by using decision.isDenied()
. To
narrow down the reason to an email validation rule, you can use
decision.reason.isEmail()
.
Checking rule results
You can iterate through the results of each rule:
for (const result of decision.results) { console.log("Rule Result", result);}
This could be useful metadata to add to a new user’s record in your database before you redirect them to the next step in your signup flow.
Custom verification logic
Checking the rule results allows you to use the Arcjet decision as part of your own verification logic. For example, you could decide to manually verify user signups that come from IP addresses associated with proxies or Tor, and any users who sign up with a free email address.
import arcjet, { protectSignup } from "@arcjet/bun";import { env } from "bun";
const aj = arcjet({ key: env.ARCJET_KEY, // Get your site key from https://app.arcjet.com // Limiting by IP is the default if not specified //characteristics: ["ip.src"], rules: [ protectSignup({ email: { mode: "LIVE", // Block emails that are disposable, invalid, or have no MX records block: ["DISPOSABLE", "INVALID", "NO_MX_RECORDS"], }, bots: { mode: "LIVE", // configured with a list of bots to allow from // https://arcjet.com/bot-list allow: [], // "allow none" will block all detected bots }, rateLimit: { // uses a sliding window rate limit mode: "LIVE", // It would be unusual for a form to be submitted more than 5 times in 10 // minutes, but you may wish to increase this. interval: "10m", max: 5, }, }), ],});
// If the signup was coming from a proxy or Tor IP address this is suspicious,// but we don't want to block them. Instead we will require manual verificationfunction isProxyOrTor(decision) { for (const result of decision.results) { if ( result.reason.isBot() && (decision.ip.isProxy() || decision.ip.isTor()) ) { return true; } } return false;}
// If the signup email address was from a free provider we want to double check// their details.function isFreeEmail(decision) { for (const result of decision.results) { if (result.reason.isEmail() && result.reason.emailTypes.includes("FREE")) { return true; } } return false;}
export default { port: 3000, fetch: aj.handler(async (req) => { // Get email from Bun request body const formData = await req.formData(); const email = formData.get("email")?.toString() ?? "";
const decision = await aj.protect(req, { // The submitted email is passed to the protect function email, });
console.log("Arcjet decision: ", decision);
if (decision.isDenied()) { if (decision.reason.isEmail()) { return new Response("Invalid email", { status: 400 }); } else { // This returns an error which is then displayed on the form, but you // could take other actions such as redirecting to an error page. return new Response("Forbidden", { status: 403 }); } } else { // At this point the signup is allowed, but we may want to take additional // verification steps const requireAdditionalVerification = isProxyOrTor(decision) || isFreeEmail(decision);
// User creation code goes here... }
return new Response("Valid email"); }),};
import arcjet, { protectSignup, type ArcjetDecision } from "@arcjet/bun";import { env } from "bun";
const aj = arcjet({ key: env.ARCJET_KEY!, // Get your site key from https://app.arcjet.com // Limiting by IP is the default if not specified //characteristics: ["ip.src"], rules: [ protectSignup({ email: { mode: "LIVE", // Block emails that are disposable, invalid, or have no MX records block: ["DISPOSABLE", "INVALID", "NO_MX_RECORDS"], }, bots: { mode: "LIVE", // configured with a list of bots to allow from // https://arcjet.com/bot-list allow: [], // "allow none" will block all detected bots }, rateLimit: { // uses a sliding window rate limit mode: "LIVE", // It would be unusual for a form to be submitted more than 5 times in 10 // minutes, but you may wish to increase this. interval: "10m", max: 5, }, }), ],});
// If the signup was coming from a proxy or Tor IP address this is suspicious,// but we don't want to block them. Instead we will require manual verificationfunction isProxyOrTor(decision: ArcjetDecision): boolean { for (const result of decision.results) { if ( result.reason.isBot() && (decision.ip.isProxy() || decision.ip.isTor()) ) { return true; } } return false;}
// If the signup email address was from a free provider we want to double check// their details.function isFreeEmail(decision: ArcjetDecision): boolean { for (const result of decision.results) { if (result.reason.isEmail() && result.reason.emailTypes.includes("FREE")) { return true; } } return false;}
export default { port: 3000, fetch: aj.handler(async (req) => { // Get email from Bun request body const formData = await req.formData(); const email = formData.get("email")?.toString() ?? "";
const decision = await aj.protect(req, { // The submitted email is passed to the protect function email, });
console.log("Arcjet decision: ", decision);
if (decision.isDenied()) { if (decision.reason.isEmail()) { return new Response("Invalid email", { status: 400 }); } else { // This returns an error which is then displayed on the form, but you // could take other actions such as redirecting to an error page. return new Response("Forbidden", { status: 403 }); } } else { // At this point the signup is allowed, but we may want to take additional // verification steps const requireAdditionalVerification = isProxyOrTor(decision) || isFreeEmail(decision);
// User creation code goes here... }
return new Response("Valid email"); }),};
import arcjet, { protectSignup } from "@arcjet/remix";
const aj = arcjet({ // Get your site key from https://app.arcjet.com and set it as an environment // variable rather than hard coding. key: process.env.ARCJET_KEY, rules: [ protectSignup({ email: { mode: "LIVE", // will block requests. Use "DRY_RUN" to log only // Block emails that are disposable, invalid, or have no MX records block: ["DISPOSABLE", "INVALID", "NO_MX_RECORDS"], }, bots: { mode: "LIVE", // configured with a list of bots to allow from // https://arcjet.com/bot-list allow: [], // "allow none" will block all detected bots }, // It would be unusual for a form to be submitted more than 5 times in 10 // minutes from the same IP address rateLimit: { // uses a sliding window rate limit mode: "LIVE", interval: "10m", // counts requests over a 10 minute sliding window max: 5, // allows 5 submissions within the window }, }), ],});
// If the signup was coming from a proxy or Tor IP address this is suspicious,// but we don't want to block them. Instead we will require manual verificationfunction isProxyOrTor(decision) { for (const result of decision.results) { if ( result.reason.isBot() && (decision.ip.isProxy() || decision.ip.isTor()) ) { return true; } } return false;}
// If the signup email address was from a free provider we want to double check// their details.function isFreeEmail(decision) { for (const result of decision.results) { if (result.reason.isEmail() && result.reason.emailTypes.includes("FREE")) { return true; } } return false;}
export async function action(args) { // The request body is a FormData object const formData = await args.request.formData(); const email = formData.get("email");
const decision = await aj.protect(args, { email }); console.log("Arcjet decision", decision);
if (decision.isDenied()) { if (decision.reason.isEmail()) { return Response.json({ error: "Invalid email." }, { status: 400 }); } else { return Response.json({ error: "Forbidden" }, { status: 403 }); } } else { // At this point the signup is allowed, but we may want to take additional // verification steps const requireAdditionalVerification = isProxyOrTor(decision) || isFreeEmail(decision);
// User creation code goes here... }
// We don't need to use the decision elsewhere, but you could return it to // the component return null;}
import arcjet, { protectSignup, ArcjetDecision } from "@arcjet/remix";import type { ActionFunctionArgs } from "@remix-run/node";
const aj = arcjet({ // Get your site key from https://app.arcjet.com and set it as an environment // variable rather than hard coding. key: process.env.ARCJET_KEY!, rules: [ protectSignup({ email: { mode: "LIVE", // will block requests. Use "DRY_RUN" to log only // Block emails that are disposable, invalid, or have no MX records block: ["DISPOSABLE", "INVALID", "NO_MX_RECORDS"], }, bots: { mode: "LIVE", // configured with a list of bots to allow from // https://arcjet.com/bot-list allow: [], // "allow none" will block all detected bots }, // It would be unusual for a form to be submitted more than 5 times in 10 // minutes from the same IP address rateLimit: { // uses a sliding window rate limit mode: "LIVE", interval: "10m", // counts requests over a 10 minute sliding window max: 5, // allows 5 submissions within the window }, }), ],});
// If the signup was coming from a proxy or Tor IP address this is suspicious,// but we don't want to block them. Instead we will require manual verificationfunction isProxyOrTor(decision: ArcjetDecision): boolean { for (const result of decision.results) { if ( result.reason.isBot() && (decision.ip.isProxy() || decision.ip.isTor()) ) { return true; } } return false;}
// If the signup email address was from a free provider we want to double check// their details.function isFreeEmail(decision: ArcjetDecision): boolean { for (const result of decision.results) { if (result.reason.isEmail() && result.reason.emailTypes.includes("FREE")) { return true; } } return false;}
export async function action(args: ActionFunctionArgs) { // The request body is a FormData object const formData = await args.request.formData(); const email = formData.get("email") as string;
const decision = await aj.protect(args, { email }); console.log("Arcjet decision", decision);
if (decision.isDenied()) { if (decision.reason.isEmail()) { return Response.json({ error: "Invalid email." }, { status: 400 }); } else { return Response.json({ error: "Forbidden" }, { status: 403 }); } } else { // At this point the signup is allowed, but we may want to take additional // verification steps const requireAdditionalVerification = isProxyOrTor(decision) || isFreeEmail(decision);
// User creation code goes here... }
// We don't need to use the decision elsewhere, but you could return it to // the component return null;}
import { env } from "$env/dynamic/private";import arcjet, { protectSignup } from "@arcjet/sveltekit";import { error, json } from "@sveltejs/kit";
const aj = arcjet({ key: env.ARCJET_KEY, // Limiting by IP is the default if not specified //characteristics: ["ip.src"], rules: [ protectSignup({ email: { mode: "LIVE", // Block emails that are disposable, invalid, or have no MX records block: ["DISPOSABLE", "INVALID", "NO_MX_RECORDS"], }, bots: { mode: "LIVE", // configured with a list of bots to allow from // https://arcjet.com/bot-list allow: [], // "allow none" will block all detected bots }, rateLimit: { // uses a sliding window rate limit mode: "LIVE", // It would be unusual for a form to be submitted more than 5 times in 10 // minutes, but you may wish to increase this. interval: "10m", max: 5, }, }), ],});
// If the signup was coming from a proxy or Tor IP address this is suspicious,// but we don't want to block them. Instead we will require manual verificationfunction isProxyOrTor(decision) { for (const result of decision.results) { if ( result.reason.isBot() && (decision.ip.isProxy() || decision.ip.isTor()) ) { return true; } } return false;}
// If the signup email address was from a free provider we want to double check// their details.function isFreeEmail(decision) { for (const result of decision.results) { if (result.reason.isEmail() && result.reason.emailTypes.includes("FREE")) { return true; } } return false;}
export async function POST(event) { const { email } = await event.request.json();
const decision = await aj.protect(event, { // The submitted email is passed to the protect function email, });
console.log("Arcjet decision: ", decision);
if (decision.isDenied()) { if (decision.reason.isEmail()) { return error(400, { message: "Invalid email" }); } else { // This returns an error which is then displayed on the form, but you // could take other actions such as redirecting to an error page return error(403, { message: "Forbidden" }); } } else { // At this point the signup is allowed, but we may want to take additional // verification steps const requireAdditionalVerification = isProxyOrTor(decision) || isFreeEmail(decision);
// User creation code goes here... }
return json({ message: "Valid email" });}
import { env } from "$env/dynamic/private";import arcjet, { protectSignup, type ArcjetDecision } from "@arcjet/sveltekit";import { error, json, type RequestEvent } from "@sveltejs/kit";
const aj = arcjet({ key: env.ARCJET_KEY!, // Limiting by IP is the default if not specified //characteristics: ["ip.src"], rules: [ protectSignup({ email: { mode: "LIVE", // Block emails that are disposable, invalid, or have no MX records block: ["DISPOSABLE", "INVALID", "NO_MX_RECORDS"], }, bots: { mode: "LIVE", // configured with a list of bots to allow from // https://arcjet.com/bot-list allow: [], // "allow none" will block all detected bots }, rateLimit: { // uses a sliding window rate limit mode: "LIVE", // It would be unusual for a form to be submitted more than 5 times in 10 // minutes, but you may wish to increase this. interval: "10m", max: 5, }, }), ],});
// If the signup was coming from a proxy or Tor IP address this is suspicious,// but we don't want to block them. Instead we will require manual verificationfunction isProxyOrTor(decision: ArcjetDecision): boolean { for (const result of decision.results) { if ( result.reason.isBot() && (decision.ip.isProxy() || decision.ip.isTor()) ) { return true; } } return false;}
// If the signup email address was from a free provider we want to double check// their details.function isFreeEmail(decision: ArcjetDecision): boolean { for (const result of decision.results) { if (result.reason.isEmail() && result.reason.emailTypes.includes("FREE")) { return true; } } return false;}
export async function POST(event: RequestEvent) { const { email } = await event.request.json();
const decision = await aj.protect(event, { // The submitted email is passed to the protect function email, });
console.log("Arcjet decision: ", decision);
if (decision.isDenied()) { if (decision.reason.isEmail()) { return error(400, { message: "Invalid email" }); } else { // This returns an error which is then displayed on the form, but you // could take other actions such as redirecting to an error page return error(403, { message: "Forbidden" }); } } else { // At this point the signup is allowed, but we may want to take additional // verification steps const requireAdditionalVerification = isProxyOrTor(decision) || isFreeEmail(decision);
// User creation code goes here... }
return json({ message: "Valid email" });}
import arcjet, { protectSignup, ArcjetDecision } from "@arcjet/next";
const aj = arcjet({ key: process.env.ARCJET_KEY, // Limiting by IP is the default if not specified //characteristics: ["ip.src"], rules: [ protectSignup({ email: { mode: "LIVE", // Block emails that are disposable, invalid, or have no MX records block: ["DISPOSABLE", "INVALID", "NO_MX_RECORDS"], }, bots: { mode: "LIVE", // configured with a list of bots to allow from // https://arcjet.com/bot-list allow: [], // "allow none" will block all detected bots }, rateLimit: { // uses a sliding window rate limit mode: "LIVE", // It would be unusual for a form to be submitted more than 5 times in 10 // minutes, but you may wish to increase this. interval: "10m", max: 5, }, }), ],});
// If the signup was coming from a proxy or Tor IP address this is suspicious,// but we don't want to block them. Instead we will require manual verificationfunction isProxyOrTor(decision) { for (const result of decision.results) { if ( result.reason.isBot() && (decision.ip.isProxy() || decision.ip.isTor()) ) { return true; } } return false;}
// If the signup email address was from a free provider we want to double check// their details.function isFreeEmail(decision) { for (const result of decision.results) { if (result.reason.isEmail() && result.reason.emailTypes.includes("FREE")) { return true; } } return false;}
export default async function handler(req, res) { const data = req.body; const email = data.email;
const decision = await aj.protect(req, { // The submitted email is passed to the protect function email, });
console.log("Arcjet decision: ", decision);
if (decision.isDenied()) { if (decision.reason.isEmail()) { return res.status(400).json({ message: "Invalid email", reason: decision.reason, }); } else { // This returns an error which is then displayed on the form, but you // could take other actions such as redirecting to an error page. See // https://nextjs.org/docs/pages/building-your-application/data-fetching/forms-and-mutations#redirecting return res.status(403).json({ message: "Forbidden", }); } } else { // At this point the signup is allowed, but we may want to take additional // verification steps const requireAdditionalVerification = isProxyOrTor(decision) || isFreeEmail(decision);
// User creation code goes here... }
res.status(200).json({ name: "Hello world" });}
import arcjet, { protectSignup, ArcjetDecision } from "@arcjet/next";import { NextResponse } from "next/server";
const aj = arcjet({ key: process.env.ARCJET_KEY!, // Limiting by IP is the default if not specified //characteristics: ["ip.src"], rules: [ protectSignup({ email: { mode: "LIVE", // Block emails that are disposable, invalid, or have no MX records block: ["DISPOSABLE", "INVALID", "NO_MX_RECORDS"], }, bots: { mode: "LIVE", // configured with a list of bots to allow from // https://arcjet.com/bot-list allow: [], // "allow none" will block all detected bots }, rateLimit: { // uses a sliding window rate limit mode: "LIVE", // It would be unusual for a form to be submitted more than 5 times in 10 // minutes, but you may wish to increase this. interval: "10m", max: 5, }, }), ],});
// If the signup was coming from a proxy or Tor IP address this is suspicious,// but we don't want to block them. Instead we will require manual verificationfunction isProxyOrTor(decision: ArcjetDecision): boolean { for (const result of decision.results) { if ( result.reason.isBot() && (decision.ip.isProxy() || decision.ip.isTor()) ) { return true; } } return false;}
// If the signup email address was from a free provider we want to double check// their details.function isFreeEmail(decision: ArcjetDecision): boolean { for (const result of decision.results) { if (result.reason.isEmail() && result.reason.emailTypes.includes("FREE")) { return true; } } return false;}
export async function POST(req: Request) { const data = await req.json(); const email = data.email;
const decision = await aj.protect(req, { // The submitted email is passed to the protect function email, });
console.log("Arcjet decision: ", decision);
if (decision.isDenied()) { if (decision.reason.isEmail()) { return NextResponse.json( { message: "Invalid email", reason: decision.reason, }, { status: 400 }, ); } else { // This returns an error which is then displayed on the form, but you // could take other actions such as redirecting to an error page. See // https://nextjs.org/docs/app/building-your-application/routing/route-handlers#redirects return NextResponse.json({ message: "Forbidden" }, { status: 403 }); } } else { // At this point the signup is allowed, but we may want to take additional // verification steps const requireAdditionalVerification = isProxyOrTor(decision) || isFreeEmail(decision);
// User creation code goes here... }
return NextResponse.json({ message: "Hello world", });}
import arcjet, { protectSignup, ArcjetDecision } from "@arcjet/next";import type { NextApiRequest, NextApiResponse } from "next";
const aj = arcjet({ key: process.env.ARCJET_KEY!, // Limiting by IP is the default if not specified //characteristics: ["ip.src"], rules: [ protectSignup({ email: { mode: "LIVE", // Block emails that are disposable, invalid, or have no MX records block: ["DISPOSABLE", "INVALID", "NO_MX_RECORDS"], }, bots: { mode: "LIVE", // configured with a list of bots to allow from // https://arcjet.com/bot-list allow: [], // "allow none" will block all detected bots }, rateLimit: { // uses a sliding window rate limit mode: "LIVE", // It would be unusual for a form to be submitted more than 5 times in 10 // minutes, but you may wish to increase this. interval: "10m", max: 5, }, }), ],});
// If the signup was coming from a proxy or Tor IP address this is suspicious,// but we don't want to block them. Instead we will require manual verificationfunction isProxyOrTor(decision: ArcjetDecision): boolean { for (const result of decision.results) { if ( result.reason.isBot() && (decision.ip.isProxy() || decision.ip.isTor()) ) { return true; } } return false;}
// If the signup email address was from a free provider we want to double check// their details.function isFreeEmail(decision: ArcjetDecision): boolean { for (const result of decision.results) { if (result.reason.isEmail() && result.reason.emailTypes.includes("FREE")) { return true; } } return false;}
export default async function handler( req: NextApiRequest, res: NextApiResponse,) { const data = req.body; const email = data.email;
const decision = await aj.protect(req, { // The submitted email is passed to the protect function email, });
console.log("Arcjet decision: ", decision);
if (decision.isDenied()) { if (decision.reason.isEmail()) { return res.status(400).json({ message: "Invalid email", reason: decision.reason, }); } else { // This returns an error which is then displayed on the form, but you // could take other actions such as redirecting to an error page. See // https://nextjs.org/docs/pages/building-your-application/data-fetching/forms-and-mutations#redirecting return res.status(403).json({ message: "Forbidden", }); } } else { // At this point the signup is allowed, but we may want to take additional // verification steps const requireAdditionalVerification = isProxyOrTor(decision) || isFreeEmail(decision);
// User creation code goes here... }
res.status(200).json({ name: "Hello world" });}
import arcjet, { protectSignup } from "@arcjet/next";import { NextResponse } from "next/server";
const aj = arcjet({ key: process.env.ARCJET_KEY, // Limiting by IP is the default if not specified //characteristics: ["ip.src"], rules: [ protectSignup({ email: { mode: "LIVE", // Block emails that are disposable, invalid, or have no MX records block: ["DISPOSABLE", "INVALID", "NO_MX_RECORDS"], }, bots: { mode: "LIVE", // configured with a list of bots to allow from // https://arcjet.com/bot-list allow: [], // "allow none" will block all detected bots }, rateLimit: { // uses a sliding window rate limit mode: "LIVE", // It would be unusual for a form to be submitted more than 5 times in 10 // minutes, but you may wish to increase this. interval: "10m", max: 5, }, }), ],});
// If the signup was coming from a proxy or Tor IP address this is suspicious,// but we don't want to block them. Instead we will require manual verificationfunction isProxyOrTor(decision) { for (const result of decision.results) { if ( result.reason.isBot() && (decision.ip.isProxy() || decision.ip.isTor()) ) { return true; } } return false;}
// If the signup email address was from a free provider we want to double check// their details.function isFreeEmail(decision) { for (const result of decision.results) { if (result.reason.isEmail() && result.reason.emailTypes.includes("FREE")) { return true; } } return false;}
export async function POST(req) { const data = await req.json(); const email = data.email;
const decision = await aj.protect(req, { // The submitted email is passed to the protect function email, });
console.log("Arcjet decision: ", decision);
if (decision.isDenied()) { if (decision.reason.isEmail()) { return NextResponse.json( { message: "Invalid email", reason: decision.reason, }, { status: 400 }, ); } else { // This returns an error which is then displayed on the form, but you // could take other actions such as redirecting to an error page. See // https://nextjs.org/docs/app/building-your-application/routing/route-handlers#redirects return NextResponse.json({ message: "Forbidden" }, { status: 403 }); } } else { // At this point the signup is allowed, but we may want to take additional // verification steps const requireAdditionalVerification = isProxyOrTor(decision) || isFreeEmail(decision);
// User creation code goes here... }
return NextResponse.json({ message: "Hello world", });}
import arcjet, { protectSignup, ArcjetDecision } from "@arcjet/node";import express from "express";
const app = express();const port = 3000;
app.use(express.urlencoded({ extended: false }));
const aj = arcjet({ // Get your site key from https://app.arcjet.com and set it as an environment // variable rather than hard coding. key: process.env.ARCJET_KEY, rules: [ protectSignup({ email: { mode: "LIVE", // will block requests. Use "DRY_RUN" to log only // Block emails that are disposable, invalid, or have no MX records block: ["DISPOSABLE", "INVALID", "NO_MX_RECORDS"], }, bots: { mode: "LIVE", // configured with a list of bots to allow from // https://arcjet.com/bot-list allow: [], // "allow none" will block all detected bots }, // It would be unusual for a form to be submitted more than 5 times in 10 // minutes from the same IP address rateLimit: { // uses a sliding window rate limit mode: "LIVE", interval: "10m", // counts requests over a 10 minute sliding window max: 5, // allows 5 submissions within the window }, }), ],});
// If the signup was coming from a proxy or Tor IP address this is suspicious,// but we don't want to block them. Instead we will require manual verificationfunction isProxyOrTor(decision) { for (const result of decision.results) { if ( result.reason.isBot() && (decision.ip.isProxy() || decision.ip.isTor()) ) { return true; } } return false;}
// If the signup email address was from a free provider we want to double check// their details.function isFreeEmail(decision) { for (const result of decision.results) { if (result.reason.isEmail() && result.reason.emailTypes.includes("FREE")) { return true; } } return false;}
app.post("/", async (req, res) => { const email = req.body.email;
const decision = await aj.protect(req, { email }); console.log("Arcjet decision", decision);
if (decision.isDenied()) { if (decision.reason.isEmail()) { // If the email is invalid then return an error message res.writeHead(400, { "Content-Type": "application/json" }); res.end( JSON.stringify({ error: "Invalid email", reason: decision.reason }), ); } else { // We get here if the client is a bot or the rate limit has been exceeded res.writeHead(403, { "Content-Type": "application/json" }); res.end(JSON.stringify({ error: "Forbidden" })); } } else { // At this point the signup is allowed, but we may want to take additional // verification steps const requireAdditionalVerification = isProxyOrTor(decision) || isFreeEmail(decision);
// User creation code goes here...
res.writeHead(200, { "Content-Type": "application/json" }); res.end(JSON.stringify({ message: "Hello World", email })); }});
app.listen(port, () => { console.log(`Example app listening on port ${port}`);});
import arcjet, { protectSignup, ArcjetDecision } from "@arcjet/node";import express from "express";
const app = express();const port = 3000;
app.use(express.urlencoded({ extended: false }));
const aj = arcjet({ // Get your site key from https://app.arcjet.com and set it as an environment // variable rather than hard coding. key: process.env.ARCJET_KEY!, rules: [ protectSignup({ email: { mode: "LIVE", // will block requests. Use "DRY_RUN" to log only // Block emails that are disposable, invalid, or have no MX records block: ["DISPOSABLE", "INVALID", "NO_MX_RECORDS"], }, bots: { mode: "LIVE", // configured with a list of bots to allow from // https://arcjet.com/bot-list allow: [], // "allow none" will block all detected bots }, // It would be unusual for a form to be submitted more than 5 times in 10 // minutes from the same IP address rateLimit: { // uses a sliding window rate limit mode: "LIVE", interval: "10m", // counts requests over a 10 minute sliding window max: 5, // allows 5 submissions within the window }, }), ],});
// If the signup was coming from a proxy or Tor IP address this is suspicious,// but we don't want to block them. Instead we will require manual verificationfunction isProxyOrTor(decision: ArcjetDecision): boolean { for (const result of decision.results) { if ( result.reason.isBot() && (decision.ip.isProxy() || decision.ip.isTor()) ) { return true; } } return false;}
// If the signup email address was from a free provider we want to double check// their details.function isFreeEmail(decision: ArcjetDecision): boolean { for (const result of decision.results) { if (result.reason.isEmail() && result.reason.emailTypes.includes("FREE")) { return true; } } return false;}
app.post("/", async (req, res) => { const email = req.body.email;
const decision = await aj.protect(req, { email }); console.log("Arcjet decision", decision);
if (decision.isDenied()) { if (decision.reason.isEmail()) { // If the email is invalid then return an error message res.writeHead(400, { "Content-Type": "application/json" }); res.end( JSON.stringify({ error: "Invalid email", reason: decision.reason }), ); } else { // We get here if the client is a bot or the rate limit has been exceeded res.writeHead(403, { "Content-Type": "application/json" }); res.end(JSON.stringify({ error: "Forbidden" })); } } else { // At this point the signup is allowed, but we may want to take additional // verification steps const requireAdditionalVerification = isProxyOrTor(decision) || isFreeEmail(decision);
// User creation code goes here...
res.writeHead(200, { "Content-Type": "application/json" }); res.end(JSON.stringify({ message: "Hello World", email })); }});
app.listen(port, () => { console.log(`Example app listening on port ${port}`);});
import { ARCJET, ArcjetDecision, type ArcjetNest, ArcjetRuleResult, protectSignup,} from "@arcjet/nest";import { Body, Controller, HttpException, HttpStatus, Inject, Injectable, Logger, Post, Req, UseInterceptors,} from "@nestjs/common";import { NoFilesInterceptor } from "@nestjs/platform-express";import { IsNotEmpty } from "class-validator";import type { Request } from "express";
// Validation class as described at// https://docs.nestjs.com/techniques/validation. We're not using the IsEmail// decorator here because Arcjet handles this for you.export class SignupDto { @IsNotEmpty() // @ts-ignore: This is a DTO class so ignore that it's not definitely assigned email: string;}
// This would normally go in your service file e.g.// src/signup/signup.service.ts@Injectable()export class SignupService { private readonly logger = new Logger(SignupService.name);
signup(email: string): { message: string } { this.logger.log(`Form submission: ${email}`);
return { message: "Hello world", }; }}
// This would normally go in your controller file e.g.// src/signup/signup.controller.ts
// If the signup was coming from a proxy or Tor IP address this is suspicious,// but we don't want to block them. Instead we will require manual verificationfunction isProxyOrTor(decision: ArcjetDecision): boolean { for (const result of decision.results) { if ( result.reason.isBot() && (decision.ip.isProxy() || decision.ip.isTor()) ) { return true; } } return false;}
// If the signup email address was from a free provider we want to double check// their details.function isFreeEmail(decision: ArcjetDecision): boolean { for (const result of decision.results) { if (result.reason.isEmail() && result.reason.emailTypes.includes("FREE")) { return true; } } return false;}
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() );}
@Controller("signup")export class SignupController { private readonly logger = new Logger(SignupController.name);
constructor( private readonly signupService: SignupService, @Inject(ARCJET) private readonly arcjet: ArcjetNest, ) {}
// Implement a form handler following // https://docs.nestjs.com/techniques/file-upload#no-files. Note this isn't // compatible with the NestJS Fastify adapter. @Post() @UseInterceptors(NoFilesInterceptor()) async index(@Req() req: Request, @Body() body: SignupDto) { const decision = await this.arcjet .withRule( protectSignup({ email: { mode: "LIVE", // will block requests. Use "DRY_RUN" to log only // Block emails that are disposable, invalid, or have no MX records block: ["DISPOSABLE", "INVALID", "NO_MX_RECORDS"], }, bots: { mode: "LIVE", // configured with a list of bots to allow from // https://arcjet.com/bot-list allow: ["CURL"], // prevents bots from submitting the form, but allow curl for this example }, // It would be unusual for a form to be submitted more than 5 times in 10 // minutes from the same IP address rateLimit: { // uses a sliding window rate limit mode: "LIVE", interval: "2m", // counts requests over a 10 minute sliding window max: 5, // allows 5 submissions within the window }, }), ) .protect(req, { email: body.email });
this.logger.log(`Arcjet: id = ${decision.id}`); this.logger.log(`Arcjet: decision = ${decision.conclusion}`);
if (decision.isDenied()) { if (decision.reason.isBot()) { throw new HttpException("No bots allowed", HttpStatus.FORBIDDEN); } else if (decision.reason.isRateLimit()) { throw new HttpException( "Too many requests", HttpStatus.TOO_MANY_REQUESTS, ); } else if (decision.reason.isEmail()) { this.logger.log(`Arcjet: email error = ${decision.reason.emailTypes}`);
let message: string;
// These are specific errors to help the user, but will also reveal the // validation to a spammer. if (decision.reason.emailTypes.includes("INVALID")) { message = "email address format is invalid. Is there a typo?"; } else if (decision.reason.emailTypes.includes("DISPOSABLE")) { message = "we do not allow disposable email addresses."; } else if (decision.reason.emailTypes.includes("NO_MX_RECORDS")) { message = "your email domain does not have an MX record. Is there a typo?"; } else { // This is a catch all, but the above should be exhaustive based on the // configured rules. message = "invalid email."; }
throw new HttpException(`Error: ${message}`, HttpStatus.BAD_REQUEST); } 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); }
// At this point the signup is allowed, but we may want to take additional // verification steps
const requireAdditionalVerification = isProxyOrTor(decision) || isFreeEmail(decision);
// User creation code goes here...
return this.signupService.signup(body.email); }}
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, { protectSignup } from "@arcjet/bun";
const aj = arcjet({ // Get your site key from https://app.arcjet.com and set it as an environment // variable rather than hard coding. key: Bun.env.ARCJET_KEY!, rules: [ protectSignup({ email: { mode: "LIVE", // will block requests. Use "DRY_RUN" to log only // Block emails that are disposable, invalid, or have no MX records block: ["DISPOSABLE", "INVALID", "NO_MX_RECORDS"], }, bots: { mode: "LIVE", // configured with a list of bots to allow from // https://arcjet.com/bot-list allow: [], // "allow none" will block all detected bots }, // It would be unusual for a form to be submitted more than 5 times in 10 // minutes from the same IP address rateLimit: { // uses a sliding window rate limit mode: "LIVE", interval: "10m", // counts requests over a 10 minute sliding window max: 5, // allows 5 submissions within the window }, }), ],});
export default { port: 3000, fetch: aj.handler(async (req) => { // Get email from Bun request body const formData = await req.formData(); const email = formData.get("email")?.toString() ?? ""; console.log("Email received: ", email);
const decision = await aj.protect(req, { email }); console.log("Arcjet decision", decision);
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()) { if (decision.reason.isEmail()) { // If the email is invalid then return an error message return new Response("Invalid email", { status: 400 }); } else { // We get here if the client is a bot or the rate limit has been exceeded return new Response("Forbidden", { status: 403 }); } }
return new Response("Hello " + email); }),};
import arcjet, { protectSignup } from "@arcjet/bun";
const aj = arcjet({ // Get your site key from https://app.arcjet.com and set it as an environment // variable rather than hard coding. key: Bun.env.ARCJET_KEY, rules: [ protectSignup({ email: { mode: "LIVE", // will block requests. Use "DRY_RUN" to log only // Block emails that are disposable, invalid, or have no MX records block: ["DISPOSABLE", "INVALID", "NO_MX_RECORDS"], }, bots: { mode: "LIVE", // configured with a list of bots to allow from // https://arcjet.com/bot-list allow: [], // "allow none" will block all detected bots }, // It would be unusual for a form to be submitted more than 5 times in 10 // minutes from the same IP address rateLimit: { // uses a sliding window rate limit mode: "LIVE", interval: "10m", // counts requests over a 10 minute sliding window max: 5, // allows 5 submissions within the window }, }), ],});
export default { port: 3000, fetch: aj.handler(async (req) => { // Get email from Bun request body const formData = await req.formData(); const email = formData.get("email")?.toString() ?? ""; console.log("Email received: ", email);
const decision = await aj.protect(req, { email }); console.log("Arcjet decision", decision);
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()) { if (decision.reason.isEmail()) { // If the email is invalid then return an error message return new Response("Invalid email", { status: 400 }); } else { // We get here if the client is a bot or the rate limit has been exceeded return new Response("Forbidden", { status: 403 }); } }
return new Response("Hello " + email); }),};
import arcjet, { protectSignup } from "@arcjet/remix";import type { ActionFunctionArgs } from "@remix-run/node";
const aj = arcjet({ // Get your site key from https://app.arcjet.com and set it as an environment // variable rather than hard coding. key: process.env.ARCJET_KEY!, rules: [ protectSignup({ email: { mode: "LIVE", // will block requests. Use "DRY_RUN" to log only // Block emails that are disposable, invalid, or have no MX records block: ["DISPOSABLE", "INVALID", "NO_MX_RECORDS"], }, bots: { mode: "LIVE", // configured with a list of bots to allow from // https://arcjet.com/bot-list allow: [], // "allow none" will block all detected bots }, // It would be unusual for a form to be submitted more than 5 times in 10 // minutes from the same IP address rateLimit: { // uses a sliding window rate limit mode: "LIVE", interval: "10m", // counts requests over a 10 minute sliding window max: 5, // allows 5 submissions within the window }, }), ],});
export async function action(args: ActionFunctionArgs) { // The request body is a FormData object const formData = await args.request.formData(); const email = formData.get("email") as string;
const decision = await aj.protect(args, { email }); console.log("Arcjet decision", decision);
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 Response.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 Response.json({ error: "Service unavailable" }, { status: 503 }); } } }
if (decision.isDenied()) { if (decision.reason.isEmail()) { return Response.json({ error: "Invalid email." }, { status: 400 }); } else { return Response.json({ error: "Forbidden" }, { status: 403 }); } }
// We don't need to use the decision elsewhere, but you could return it to // the component return null;}
import arcjet, { protectSignup } from "@arcjet/remix";
const aj = arcjet({ // Get your site key from https://app.arcjet.com and set it as an environment // variable rather than hard coding. key: process.env.ARCJET_KEY, rules: [ protectSignup({ email: { mode: "LIVE", // will block requests. Use "DRY_RUN" to log only // Block emails that are disposable, invalid, or have no MX records block: ["DISPOSABLE", "INVALID", "NO_MX_RECORDS"], }, bots: { mode: "LIVE", // configured with a list of bots to allow from // https://arcjet.com/bot-list allow: [], // "allow none" will block all detected bots }, // It would be unusual for a form to be submitted more than 5 times in 10 // minutes from the same IP address rateLimit: { // uses a sliding window rate limit mode: "LIVE", interval: "10m", // counts requests over a 10 minute sliding window max: 5, // allows 5 submissions within the window }, }), ],});
export async function action(args) { // The request body is a FormData object const formData = await args.request.formData(); const email = formData.get("email");
const decision = await aj.protect(args, { email }); console.log("Arcjet decision", decision);
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 Response.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 Response.json({ error: "Service unavailable" }, { status: 503 }); } } }
if (decision.isDenied()) { if (decision.reason.isEmail()) { return Response.json({ error: "Invalid email." }, { status: 400 }); } else { return Response.json({ error: "Forbidden" }, { status: 403 }); } }
// We don't need to use the decision elsewhere, but you could return it to // the component return null;}
import arcjet, { protectSignup } from "@arcjet/next";
const aj = arcjet({ key: process.env.ARCJET_KEY, rules: [ protectSignup({ email: { mode: "LIVE", block: ["DISPOSABLE", "INVALID", "NO_MX_RECORDS"], }, bots: { mode: "LIVE", allow: [], }, rateLimit: { mode: "LIVE", interval: "10m", max: 5, }, }), ],});
export default async function handler(req, res) { const data = req.body; const email = data.email;
const decision = await aj.protect(req, { // The submitted email is passed to the protect function email, });
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 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()) { if (decision.reason.isEmail()) { return res.status(400).json({ message: "Invalid email", reason: decision.reason, }); } else { // This returns an error which is then displayed on the form, but you // could take other actions such as redirecting to an error page. See // https://nextjs.org/docs/pages/building-your-application/data-fetching/forms-and-mutations#redirecting return res.status(403).json({ message: "Forbidden", }); } } else { // The form submission is allowed to proceed so do something with it here
res.status(200).json({ name: "Hello world" }); }}
import arcjet, { protectSignup } from "@arcjet/next";import { NextResponse } from "next/server";
const aj = arcjet({ key: process.env.ARCJET_KEY!, rules: [ protectSignup({ email: { mode: "LIVE", block: ["DISPOSABLE", "INVALID", "NO_MX_RECORDS"], }, bots: { mode: "LIVE", allow: [], }, rateLimit: { mode: "LIVE", interval: "10m", max: 5, }, }), ],});
export async function POST(req: Request) { const data = await req.json(); const email = data.email;
const decision = await aj.protect(req, { // The submitted email is passed to the protect function email, });
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 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()) { if (decision.reason.isEmail()) { return NextResponse.json( { message: "Invalid email", reason: decision.reason, }, { status: 400 }, ); } else { // This returns an error which is then displayed on the form, but you // could take other actions such as redirecting to an error page. See // https://nextjs.org/docs/pages/building-your-application/data-fetching/forms-and-mutations#redirecting return NextResponse.json({ message: "Forbidden" }, { status: 403 }); } } else { // The form submission is allowed to proceed so do something with it here
return NextResponse.json({ message: "Hello world", }); }}
import arcjet, { protectSignup } from "@arcjet/next";import { NextResponse } from "next/server";
const aj = arcjet({ key: process.env.ARCJET_KEY, rules: [ protectSignup({ email: { mode: "LIVE", block: ["DISPOSABLE", "INVALID", "NO_MX_RECORDS"], }, bots: { mode: "LIVE", allow: [], }, rateLimit: { mode: "LIVE", interval: "10m", max: 5, }, }), ],});
export async function POST(req) { const data = await req.json(); const email = data.email;
const decision = await aj.protect(req, { // The submitted email is passed to the protect function email, });
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 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()) { if (decision.reason.isEmail()) { return NextResponse.json( { message: "Invalid email", reason: decision.reason, }, { status: 400 }, ); } else { // This returns an error which is then displayed on the form, but you // could take other actions such as redirecting to an error page. See // https://nextjs.org/docs/pages/building-your-application/data-fetching/forms-and-mutations#redirecting return NextResponse.json({ message: "Forbidden" }, { status: 403 }); } } else { // The form submission is allowed to proceed so do something with it here
return NextResponse.json({ message: "Hello world", }); }}
import arcjet, { protectSignup } from "@arcjet/next";import type { NextApiRequest, NextApiResponse } from "next";
const aj = arcjet({ key: process.env.ARCJET_KEY!, rules: [ protectSignup({ email: { mode: "LIVE", block: ["DISPOSABLE", "INVALID", "NO_MX_RECORDS"], }, bots: { mode: "LIVE", allow: [], }, rateLimit: { mode: "LIVE", interval: "10m", max: 5, }, }), ],});
export default async function handler( req: NextApiRequest, res: NextApiResponse,) { const data = req.body; const email = data.email;
const decision = await aj.protect(req, { // The submitted email is passed to the protect function email, });
if (decision.isErrored()) { // Fail open by logging the error and continuing console.warn("Arcjet error", decision.reason.message); // You could also fail closed here for very sensitive routes //return res.status(503).json({ error: "Service unavailable" }); }
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 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()) { if (decision.reason.isEmail()) { return res.status(400).json({ message: "Invalid email", reason: decision.reason, }); } else { // This returns an error which is then displayed on the form, but you // could take other actions such as redirecting to an error page. See // https://nextjs.org/docs/pages/building-your-application/data-fetching/forms-and-mutations#redirecting return res.status(403).json({ message: "Forbidden", }); } } else { // The form submission is allowed to proceed so do something with it here
res.status(200).json({ name: "Hello world" }); }}
import { env } from "$env/dynamic/private";import arcjet, { protectSignup } from "@arcjet/sveltekit";import { error, json, type RequestEvent } from "@sveltejs/kit";
const aj = arcjet({ key: env.ARCJET_KEY!, // Limiting by IP is the default if not specified //characteristics: ["ip.src"], rules: [ protectSignup({ email: { mode: "LIVE", // Block emails that are disposable, invalid, or have no MX records block: ["DISPOSABLE", "INVALID", "NO_MX_RECORDS"], }, bots: { mode: "LIVE", // configured with a list of bots to allow from // https://arcjet.com/bot-list allow: [], // "allow none" will block all detected bots }, rateLimit: { // uses a sliding window rate limit mode: "LIVE", // It would be unusual for a form to be submitted more than 5 times in 10 // minutes, but you may wish to increase this. interval: "10m", max: 5, }, }), ],});
export async function POST(event: RequestEvent) { const { email } = await event.request.json();
const decision = await aj.protect(event, { // The submitted email is passed to the protect function email, });
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()) { if (decision.reason.isEmail()) { return error(400, { message: "Invalid email" }); } else { // This returns an error which is then displayed on the form, but you // could take other actions such as redirecting to an error page return error(403, { message: "Forbidden" }); } } else { // User creation code goes here... }
return json({ message: "Valid email" });}
import { env } from "$env/dynamic/private";import arcjet, { protectSignup } from "@arcjet/sveltekit";import { error, json } from "@sveltejs/kit";
const aj = arcjet({ key: env.ARCJET_KEY, // Limiting by IP is the default if not specified //characteristics: ["ip.src"], rules: [ protectSignup({ email: { mode: "LIVE", // Block emails that are disposable, invalid, or have no MX records block: ["DISPOSABLE", "INVALID", "NO_MX_RECORDS"], }, bots: { mode: "LIVE", // configured with a list of bots to allow from // https://arcjet.com/bot-list allow: [], // "allow none" will block all detected bots }, rateLimit: { // uses a sliding window rate limit mode: "LIVE", // It would be unusual for a form to be submitted more than 5 times in 10 // minutes, but you may wish to increase this. interval: "10m", max: 5, }, }), ],});
export async function POST(event) { const { email } = await event.request.json();
const decision = await aj.protect(event, { // The submitted email is passed to the protect function email, });
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()) { if (decision.reason.isEmail()) { return error(400, { message: "Invalid email" }); } else { // This returns an error which is then displayed on the form, but you // could take other actions such as redirecting to an error page return error(403, { message: "Forbidden" }); } } else { // User creation code goes here... }
return json({ message: "Valid email" });}
import arcjet, { protectSignup } from "@arcjet/node";import express from "express";
const app = express();const port = 3000;
app.use(express.urlencoded({ extended: false }));
const aj = arcjet({ // Get your site key from https://app.arcjet.com and set it as an environment // variable rather than hard coding. key: process.env.ARCJET_KEY!, rules: [ protectSignup({ email: { mode: "LIVE", // will block requests. Use "DRY_RUN" to log only // Block emails that are disposable, invalid, or have no MX records block: ["DISPOSABLE", "INVALID", "NO_MX_RECORDS"], }, bots: { mode: "LIVE", // configured with a list of bots to allow from // https://arcjet.com/bot-list allow: [], // "allow none" will block all detected bots }, // It would be unusual for a form to be submitted more than 5 times in 10 // minutes from the same IP address rateLimit: { // uses a sliding window rate limit mode: "LIVE", interval: "10m", // counts requests over a 10 minute sliding window max: 5, // allows 5 submissions within the window }, }), ],});
app.post("/", async (req, res) => { console.log("Email received: ", req.body.email);
const decision = await aj.protect(req, { email: req.body.email, }); console.log("Arcjet decision", decision);
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()) { if (decision.reason.isEmail()) { // If the email is invalid then return an error message res.writeHead(400, { "Content-Type": "application/json" }); res.end( JSON.stringify({ error: "Invalid email", reason: decision.reason }), ); } else { // We get here if the client is a bot or the rate limit has been exceeded 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", email: req.body.email })); }});
app.listen(port, () => { console.log(`Example app listening on port ${port}`);});
import arcjet, { protectSignup } from "@arcjet/node";import express from "express";
const app = express();const port = 3000;
app.use(express.urlencoded({ extended: false }));
const aj = arcjet({ // Get your site key from https://app.arcjet.com and set it as an environment // variable rather than hard coding. key: process.env.ARCJET_KEY, rules: [ protectSignup({ email: { mode: "LIVE", // will block requests. Use "DRY_RUN" to log only // Block emails that are disposable, invalid, or have no MX records block: ["DISPOSABLE", "INVALID", "NO_MX_RECORDS"], }, bots: { mode: "LIVE", // configured with a list of bots to allow from // https://arcjet.com/bot-list allow: [], // "allow none" will block all detected bots }, // It would be unusual for a form to be submitted more than 5 times in 10 // minutes from the same IP address rateLimit: { // uses a sliding window rate limit mode: "LIVE", interval: "10m", // counts requests over a 10 minute sliding window max: 5, // allows 5 submissions within the window }, }), ],});
app.post("/", async (req, res) => { console.log("Email received: ", req.body.email);
const decision = await aj.protect(req, { email: req.body.email, }); console.log("Arcjet decision", decision);
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()) { if (decision.reason.isEmail()) { // If the email is invalid then return an error message res.writeHead(400, { "Content-Type": "application/json" }); res.end( JSON.stringify({ error: "Invalid email", reason: decision.reason }), ); } else { // We get here if the client is a bot or the rate limit has been exceeded 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", email: req.body.email })); }});
app.listen(port, () => { console.log(`Example app listening on port ${port}`);});
import { ARCJET, type ArcjetNest, ArcjetRuleResult, protectSignup,} from "@arcjet/nest";import { Body, Controller, HttpException, HttpStatus, Inject, Injectable, Logger, Post, Req, UseInterceptors,} from "@nestjs/common";import { NoFilesInterceptor } from "@nestjs/platform-express";import { IsNotEmpty } from "class-validator";import type { Request } from "express";
// Validation class as described at// https://docs.nestjs.com/techniques/validation. We're not using the IsEmail// decorator here because Arcjet handles this for you.export class SignupDto { @IsNotEmpty() // @ts-ignore: This is a DTO class so ignore that it's not definitely assigned email: string;}
// This would normally go in your service file e.g.// src/signup/signup.service.ts@Injectable()export class SignupService { private readonly logger = new Logger(SignupService.name);
signup(email: string): { message: string } { this.logger.log(`Form submission: ${email}`);
return { message: "Hello world", }; }}
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 controller file e.g.// src/signup/signup.controller.ts@Controller("signup")export class SignupController { private readonly logger = new Logger(SignupController.name);
constructor( private readonly signupService: SignupService, @Inject(ARCJET) private readonly arcjet: ArcjetNest, ) {}
// Implement a form handler following // https://docs.nestjs.com/techniques/file-upload#no-files. Note this isn't // compatible with the NestJS Fastify adapter. @Post() @UseInterceptors(NoFilesInterceptor()) async index(@Req() req: Request, @Body() body: SignupDto) { const decision = await this.arcjet .withRule( protectSignup({ email: { mode: "LIVE", // will block requests. Use "DRY_RUN" to log only // Block emails that are disposable, invalid, or have no MX records block: ["DISPOSABLE", "INVALID", "NO_MX_RECORDS"], }, bots: { mode: "LIVE", // configured with a list of bots to allow from // https://arcjet.com/bot-list allow: ["CURL"], // prevents bots from submitting the form, but allow curl for this example }, // It would be unusual for a form to be submitted more than 5 times in 10 // minutes from the same IP address rateLimit: { // uses a sliding window rate limit mode: "LIVE", interval: "2m", // counts requests over a 10 minute sliding window max: 5, // allows 5 submissions within the window }, }), ) .protect(req, { email: body.email });
this.logger.log(`Arcjet: id = ${decision.id}`); this.logger.log(`Arcjet: decision = ${decision.conclusion}`);
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 HttpException("Bad request", HttpStatus.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 //throw new HttpException("Forbidden", HttpStatus.FORBIDDEN); } } }
if (decision.isDenied()) { if (decision.reason.isBot()) { throw new HttpException("No bots allowed", HttpStatus.FORBIDDEN); } else if (decision.reason.isRateLimit()) { throw new HttpException( "Too many requests", HttpStatus.TOO_MANY_REQUESTS, ); } else if (decision.reason.isEmail()) { this.logger.log(`Arcjet: email error = ${decision.reason.emailTypes}`);
let message: string;
// These are specific errors to help the user, but will also reveal the // validation to a spammer. if (decision.reason.emailTypes.includes("INVALID")) { message = "email address format is invalid. Is there a typo?"; } else if (decision.reason.emailTypes.includes("DISPOSABLE")) { message = "we do not allow disposable email addresses."; } else if (decision.reason.emailTypes.includes("NO_MX_RECORDS")) { message = "your email domain does not have an MX record. Is there a typo?"; } else { // This is a catch all, but the above should be exhaustive based on the // configured rules. message = "invalid email."; }
throw new HttpException(`Error: ${message}`, HttpStatus.BAD_REQUEST); } 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.signupService.signup(body.email); }}
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.