### Start Server (Python) Source: https://github.com/arcjet/arcjet-docs/blob/main/src/content/docs/email-validation/quick-start.mdx Start your Python application server. This example uses Uvicorn for FastAPI and the Flask development server. ```bash uvicorn main:app --reload flask run ``` -------------------------------- ### Example: Allow non-VPN, US-based GET requests (SvelteKit) Source: https://github.com/arcjet/arcjet-docs/blob/main/src/content/docs/filters/reference.mdx This SvelteKit example demonstrates how to allow non-VPN, US-based GET requests. Requests matching the expression are allowed, and all others are denied. ```javascript import { filter } from "@arcjet/sveltekit"; export default filter({ mode: "live" }, async (request) => { // Allow non-VPN, US-based GET requests if ( request.method === "GET" && request.headers.get("cf-ipcountry") === "US" && !request.headers.get("x-arcjet-vpn") ) { return "allow"; } }); ``` -------------------------------- ### Example: Allow non-VPN, US-based GET requests (Deno) Source: https://github.com/arcjet/arcjet-docs/blob/main/src/content/docs/filters/reference.mdx This Deno example demonstrates how to allow non-VPN, US-based GET requests. Requests matching the expression are allowed, and all others are denied. ```javascript import { filter } from "@arcjet/deno"; export default filter({ mode: "live" }, async (request) => { // Allow non-VPN, US-based GET requests if ( request.method === "GET" && request.headers.get("cf-ipcountry") === "US" && !request.headers.get("x-arcjet-vpn") ) { return "allow"; } }); ``` -------------------------------- ### Example: Allow non-VPN, US-based GET requests (Bun) Source: https://github.com/arcjet/arcjet-docs/blob/main/src/content/docs/filters/reference.mdx This Bun example demonstrates how to allow non-VPN, US-based GET requests. Requests matching the expression are allowed, and all others are denied. ```javascript import { filter } from "@arcjet/bun"; export default filter({ mode: "live" }, async (request) => { // Allow non-VPN, US-based GET requests if ( request.method === "GET" && request.headers.get("cf-ipcountry") === "US" && !request.headers.get("x-arcjet-vpn") ) { return "allow"; } }); ``` -------------------------------- ### Example: Allow non-VPN, US-based GET requests (Remix) Source: https://github.com/arcjet/arcjet-docs/blob/main/src/content/docs/filters/reference.mdx This Remix example demonstrates how to allow non-VPN, US-based GET requests. Requests matching the expression are allowed, and all others are denied. ```javascript import { filter } from "@arcjet/remix"; export default filter({ mode: "live" }, async (request) => { // Allow non-VPN, US-based GET requests if ( request.method === "GET" && request.headers.get("cf-ipcountry") === "US" && !request.headers.get("x-arcjet-vpn") ) { return "allow"; } }); ``` -------------------------------- ### Recommended Signup Protection Setup Source: https://github.com/arcjet/arcjet-docs/blob/main/src/content/docs/signup-protection/reference.mdx Use this snippet to quickly integrate Arcjet's recommended signup protection. Ensure you have the necessary Arcjet SDK installed for your framework. ```javascript import { Arcjet } from "@arcjet/next"; const arcjet = new Arcjet(); export default async function handler(req, res) { const result = await arcjet.protect( () => fetch("https://api.example.com/signup", { method: "POST", body: JSON.stringify(req.body), headers: { "Content-Type": "application/json", }, }), { ip: req.socket.remoteAddress, email: req.body.email } ); if (result.isDenied) { return res.status(403).json({ message: "Access denied" }); } return res.status(200).json({ message: "Signup successful" }); } ``` ```javascript import { Arcjet } from "@arcjet/remix"; const arcjet = new Arcjet(); export const action = async ({ request }) => { const formData = await request.formData(); const email = formData.get("email"); const result = await arcjet.protect( () => fetch("https://api.example.com/signup", { method: "POST", body: JSON.stringify(Object.fromEntries(formData)), headers: { "Content-Type": "application/json", }, }), { ip: request.ip, email: email } ); if (result.isDenied) { throw new Response("Access denied", { status: 403 }); } return new Response("Signup successful", { status: 200 }); }; ``` ```javascript import { Arcjet } from "@arcjet/sveltekit"; const arcjet = new Arcjet(); export const actions = { default: async (event) => { const data = await event.request.formData(); const email = data.get("email"); const result = await arcjet.protect( () => fetch("https://api.example.com/signup", { method: "POST", body: JSON.stringify(Object.fromEntries(data)), headers: { "Content-Type": "application/json", }, }), { ip: event.getClientAddress(), email: email } ); if (result.isDenied) { return { error: "Access denied", status: 403, }; } return { message: "Signup successful", status: 200, }; }, }; ``` ```javascript import { Arcjet } from "@arcjet/bun"; const arcjet = new Arcjet(); export default { async fetch(request) { const url = new URL(request.url); const email = url.searchParams.get("email"); const result = await arcjet.protect( () => fetch("https://api.example.com/signup", { method: "POST", body: JSON.stringify({ email: email }), headers: { "Content-Type": "application/json", }, }), { ip: request.headers.get("cf-connecting-ip"), email: email } ); if (result.isDenied) { return new Response("Access denied", { status: 403 }); } return new Response("Signup successful", { status: 200 }); }, }; ``` ```javascript import { Arcjet } from "@arcjet/nodejs"; export default async function handler(req, res) { const arcjet = new Arcjet(); const email = req.body.email; const result = await arcjet.protect( () => fetch("https://api.example.com/signup", { method: "POST", body: JSON.stringify(req.body), headers: { "Content-Type": "application/json", }, }), { ip: req.socket.remoteAddress, email: email } ); if (result.isDenied) { return res.status(403).json({ message: "Access denied" }); } return res.status(200).json({ message: "Signup successful" }); } ``` ```javascript import { Arcjet } from "@arcjet/nestjs"; import { Controller, Post, Body, Req, Res } from "@nestjs/common"; @Controller("signup") export class SignupController { constructor(private readonly arcjet: Arcjet) {} @Post() async signup(@Body() body, @Req() req, @Res() res) { const email = body.email; const result = await this.arcjet.protect( () => fetch("https://api.example.com/signup", { method: "POST", body: JSON.stringify(body), headers: { "Content-Type": "application/json", }, }), { ip: req.socket.remoteAddress, email: email } ); if (result.isDenied) { return res.status(403).json({ message: "Access denied" }); } return res.status(200).json({ message: "Signup successful" }); } } ``` -------------------------------- ### JavaScript Example for Step 3 Source: https://github.com/arcjet/arcjet-docs/blob/main/src/snippets/sensitive-info/quick-start/nodejs/Step3.mdx This JavaScript code snippet demonstrates the implementation for Step 3 of the Arcjet quick start guide. It shows how to integrate Arcjet into your application. ```js import { Arcjet, OpenAI } from "@arcjet/next"; const arcjet = new Arcjet({ // Use environment variables for your API key // ARCJET_API_KEY: process.env.ARCJET_API_KEY, }); const openAI = OpenAI.withArcjet(arcjet, { // Your OpenAI API key // OPENAI_API_KEY: process.env.OPENAI_API_KEY, }); export default async function handler(req, res) { const prompt = "Tell me a joke"; try { const aiResponse = await openAI.chat.completions.create({ model: "gpt-3.5-turbo", messages: [{ role: "user", content: prompt }], }); res.status(200).json({ response: aiResponse.choices[0].message.content }); } catch (error) { console.error("Error calling OpenAI:", error); res.status(500).json({ error: "Failed to get response from AI" }); } } ``` -------------------------------- ### Start Server Source: https://github.com/arcjet/arcjet-docs/blob/main/src/content/docs/signup-protection/quick-start.mdx Start your server to begin protecting your signup forms. The command varies depending on your framework. ```bash bun --hot src/index.ts ``` ```bash npm run dev ``` ```bash uvicorn main:app --reload ``` ```bash flask run ``` ```bash npm run dev ``` ```bash npm run dev ``` ```bash npm run dev ``` ```bash npm run dev ``` -------------------------------- ### TypeScript Example for Step 3 Source: https://github.com/arcjet/arcjet-docs/blob/main/src/snippets/sensitive-info/quick-start/nodejs/Step3.mdx This TypeScript code snippet demonstrates the implementation for Step 3 of the Arcjet quick start guide. It shows how to integrate Arcjet into your application. ```ts import { Arcjet, OpenAI } from "@arcjet/next"; const arcjet = new Arcjet({ // Use environment variables for your API key // ARCJET_API_KEY: process.env.ARCJET_API_KEY, }); const openAI = OpenAI.withArcjet(arcjet, { // Your OpenAI API key // OPENAI_API_KEY: process.env.OPENAI_API_KEY, }); export default async function handler(req, res) { const prompt = "Tell me a joke"; try { const aiResponse = await openAI.chat.completions.create({ model: "gpt-3.5-turbo", messages: [{ role: "user", content: prompt }], }); res.status(200).json({ response: aiResponse.choices[0].message.content }); } catch (error) { console.error("Error calling OpenAI:", error); res.status(500).json({ error: "Failed to get response from AI" }); } } ``` -------------------------------- ### Initialize FastAPI Project and Install Dependencies Source: https://github.com/arcjet/arcjet-docs/blob/main/src/snippets/get-started/python-fastapi/Step1.mdx Create a new project directory, initialize a Python virtual environment using uv, and install Arcjet, FastAPI, Uvicorn, and Langchain packages. ```shell mkdir arcjet-fastapi cd arcjet-fastapi uv init uv add arcjet fastapi uvicorn langchain langchain-openai ``` -------------------------------- ### Install logging packages Source: https://github.com/arcjet/arcjet-docs/blob/main/src/content/docs/reference/nodejs.mdx Install Pino and pino-pretty for structured and pretty-printed logging. ```shell npm install pino pino-pretty ``` -------------------------------- ### Example: Allow non-VPN, US-based GET requests (Flask) Source: https://github.com/arcjet/arcjet-docs/blob/main/src/content/docs/filters/reference.mdx This Flask example demonstrates how to allow non-VPN, US-based GET requests. Requests matching the expression are allowed, and all others are denied. ```python from arcjet import filter_request @app.route("/api") def handler(request): # Allow non-VPN, US-based GET requests if ( request.method == "GET" and request.headers.get("cf-ipcountry") == "US" and not request.headers.get("x-arcjet-vpn") ): return "allow" return filter_request(request, allow=[ "method == \"GET\"", "headers.cf_ipcountry == \"US\"", "!headers.x_arcjet_vpn" ]) ``` -------------------------------- ### Example: Allow non-VPN, US-based GET requests (FastAPI) Source: https://github.com/arcjet/arcjet-docs/blob/main/src/content/docs/filters/reference.mdx This FastAPI example demonstrates how to allow non-VPN, US-based GET requests. Requests matching the expression are allowed, and all others are denied. ```python from arcjet import filter_request @app.route("/api") async def handler(request): # Allow non-VPN, US-based GET requests if ( request.method == "GET" and request.headers.get("cf-ipcountry") == "US" and not request.headers.get("x-arcjet-vpn") ): return "allow" return filter_request(request, allow=[ "method == \"GET\"", "headers.cf_ipcountry == \"US\"", "!headers.x_arcjet_vpn" ]) ``` -------------------------------- ### Recommended Signup Protection Setup in TypeScript Source: https://github.com/arcjet/arcjet-docs/blob/main/src/snippets/signup-protection/reference/bun/Recommended.mdx This snippet shows the recommended way to set up signup protection using TypeScript with Bun. Ensure you have the necessary imports and configurations in place. ```typescript import { Arcjet, protect } from "@arcjet/bun"; const arcjet = new Arcjet({ token: process.env.ARCJET_KEY }); export default { async fetch(request: Request): Promise { constsschutz = await protect(request, { // Optional: Customize rules, rate limits, etc. // Example: Block IPs that have made more than 100 requests in 1 minute rules: [ { name: "rate-limit-100-per-minute", type: "rate-limit", window: 60, count: 100, }, ], }); if (schutz.isBlocked) { return new Response(schutz.blockReason, { status: 429 }); } // Your application logic here return new Response("Hello World!"); }, }; ``` -------------------------------- ### Start Deno Application Source: https://github.com/arcjet/arcjet-docs/blob/main/public/llms-full.txt Run the Deno application with necessary network and environment variable permissions. ```shell deno run --allow-net --allow-env index.ts ``` -------------------------------- ### Fastify Server Setup (JavaScript) Source: https://github.com/arcjet/arcjet-docs/blob/main/src/snippets/get-started/fastify/Step3.mdx Create a new file at `server.js` with the provided JavaScript code for your Fastify server. This snippet includes the necessary setup for a basic Fastify application. ```js const Fastify = require('fastify') const app = Fastify({ logger: true }) app.get('/', async (_request, reply) => { return { hello: 'world' } }) const start = async () => { try { await app.listen({ port: 3000 }) } catch (err) { app.log.error(err) process.exit(1) } } start() ``` -------------------------------- ### Example: Allow non-VPN, US-based GET requests (NestJS) Source: https://github.com/arcjet/arcjet-docs/blob/main/src/content/docs/filters/reference.mdx This NestJS example demonstrates how to allow non-VPN, US-based GET requests. Requests matching the expression are allowed, and all others are denied. ```javascript import { filter } from "@arcjet/nest-js"; export default filter({ mode: "live" }, async (request) => { // Allow non-VPN, US-based GET requests if ( request.method === "GET" && request.headers.get("cf-ipcountry") === "US" && !request.headers.get("x-arcjet-vpn") ) { return "allow"; } }); ``` -------------------------------- ### Start Server (Bun) Source: https://github.com/arcjet/arcjet-docs/blob/main/src/content/docs/rate-limiting/quick-start.mdx Start your Bun development server. Ensure the ARCJET_KEY environment variable is set. ```bash bun --watch src/index.ts ``` -------------------------------- ### Start Server (Node.js/Bun) Source: https://github.com/arcjet/arcjet-docs/blob/main/src/content/docs/email-validation/quick-start.mdx Start your Node.js or Bun server. Ensure the ARCJET_API_KEY environment variable is set before running. ```bash node index.js bun run index.js ``` -------------------------------- ### Start Server with Bun (JavaScript) Source: https://github.com/arcjet/arcjet-docs/blob/main/src/snippets/email-validation/quick-start/bun/Step4.mdx Use this command to start your server in development mode with hot-reloading for JavaScript files. Ensure your main file is named index.js. ```sh bun run --hot index.js ``` -------------------------------- ### Example: Allow non-VPN, US-based GET requests (Node.js) Source: https://github.com/arcjet/arcjet-docs/blob/main/src/content/docs/filters/reference.mdx This Node.js example demonstrates how to allow non-VPN, US-based GET requests. Requests matching the expression are allowed, and all others are denied. ```javascript import { filter } from "@arcjet/nextjs"; export default filter({ mode: "live" }, async (request) => { // Allow non-VPN, US-based GET requests if ( request.method === "GET" && request.headers.get("cf-ipcountry") === "US" && !request.headers.get("x-arcjet-vpn") ) { return "allow"; } }); ``` -------------------------------- ### Install Arcjet with uv Source: https://github.com/arcjet/arcjet-docs/blob/main/src/content/docs/reference/python.mdx Install the Arcjet Python SDK using uv. ```sh uv add arcjet ``` -------------------------------- ### Install @nosecone/sveltekit Source: https://github.com/arcjet/arcjet-docs/blob/main/src/content/docs/nosecone/reference.mdx Install the Nosecone SvelteKit adapter using npm, pnpm, or yarn. ```sh npm i @nosecone/sveltekit ``` ```sh pnpm add @nosecone/sveltekit ``` ```sh yarn add @nosecone/sveltekit ``` -------------------------------- ### Manually Install Arcjet Astro Package (yarn) Source: https://github.com/arcjet/arcjet-docs/blob/main/src/snippets/shared/astro/Install.mdx Manually install the Arcjet Astro package using yarn as part of the integration setup. ```sh yarn add @arcjet/astro ``` -------------------------------- ### Fastify Server Setup (TypeScript) Source: https://github.com/arcjet/arcjet-docs/blob/main/src/snippets/get-started/fastify/Step3.mdx Create a new file at `server.ts` with the provided TypeScript code for your Fastify server. This snippet includes the necessary setup for a basic Fastify application. ```ts import Fastify from 'fastify' const app = Fastify({ logger: true }) app.get('/', async (_request, reply) => { return { hello: 'world' } }) const start = async () => { try { await app.listen({ port: 3000 }) } catch (err) { app.log.error(err) process.exit(1) } } start() ``` -------------------------------- ### Manually Install Arcjet Astro Package (pnpm) Source: https://github.com/arcjet/arcjet-docs/blob/main/src/snippets/shared/astro/Install.mdx Manually install the Arcjet Astro package using pnpm as part of the integration setup. ```sh pnpm add @arcjet/astro ``` -------------------------------- ### Manually Install Arcjet Astro Package (npm) Source: https://github.com/arcjet/arcjet-docs/blob/main/src/snippets/shared/astro/Install.mdx Manually install the Arcjet Astro package using npm as part of the integration setup. ```sh npm add @arcjet/astro ``` -------------------------------- ### Python Configuration Examples Source: https://github.com/arcjet/arcjet-docs/blob/main/tests/llms-txt.test.ts-snapshots/llms-full-chromium-darwin.md Examples of configuring Arcjet rules using Python, demonstrating different rule types and parameter formats. ```python shield(mode=Mode.LIVE) ``` ```python detect_bot(mode=Mode.LIVE, allow=[BotCategory.SEARCH_ENGINE]) ``` ```python detect_bot(mode=Mode.LIVE, allow=["CURL"]) ``` ```python token_bucket(mode=Mode.LIVE, refill_rate=100, interval=60, capacity=1000, characteristics=["userId"]) ``` ```python fixed_window(mode=Mode.LIVE, window=60, max=100) ``` ```python sliding_window(mode=Mode.LIVE, interval=60, max=100) ``` -------------------------------- ### Install Arcjet Source: https://github.com/arcjet/arcjet-docs/blob/main/src/content/docs/filters/quick-start.mdx Install the Arcjet SDK for your framework. This is the first step in setting up Arcjet filters. ```bash npm install @arcjet/astro # or yarn add @arcjet/astro # or pnpm add @arcjet/astro ``` ```bash npm install @arcjet/bun # or yarn add @arcjet/bun # or pnpm add @arcjet/bun ``` ```bash npm install @arcjet/deno # or yarn add @arcjet/deno # or pnpm add @arcjet/deno ``` ```bash npm install @arcjet/fastify # or yarn add @arcjet/fastify # or pnpm add @arcjet/fastify ``` ```bash npm install @arcjet/nestjs # or yarn add @arcjet/nestjs # or pnpm add @arcjet/nestjs ``` ```bash npm install @arcjet/nextjs # or yarn add @arcjet/nextjs # or pnpm add @arcjet/nextjs ``` ```bash npm install @arcjet/nodejs # or yarn add @arcjet/nodejs # or pnpm add @arcjet/nodejs ``` ```bash pip install arcjet ``` ```bash pip install arcjet ``` ```bash npm install @arcjet/react-router # or yarn add @arcjet/react-router # or pnpm add @arcjet/react-router ``` ```bash npm install @arcjet/remix # or yarn add @arcjet/remix # or pnpm add @arcjet/remix ``` ```bash npm install @arcjet/sveltekit # or yarn add @arcjet/sveltekit # or pnpm add @arcjet/sveltekit ``` -------------------------------- ### Email Validation Setup (JavaScript) Source: https://github.com/arcjet/arcjet-docs/blob/main/src/snippets/email-validation/quick-start/nodejs/Step3.mdx This JavaScript code snippet illustrates the setup for email validation. It mirrors the TypeScript example, providing an alternative for JavaScript-based projects. ```js import Step3JS from "./Step3.js?raw"; import { Code } from "@astrojs/starlight/components"; import SelectableContent from "@/components/SelectableContent";
``` -------------------------------- ### Initialize Flask Project and Add Dependencies Source: https://github.com/arcjet/arcjet-docs/blob/main/src/snippets/get-started/python-flask/Step1.mdx Use uv to create a new Flask project directory, initialize its environment, and add Arcjet, Flask, and Langchain packages. ```shell mkdir arcjet-flask cd arcjet-flask uv init uv add arcjet flask langchain langchain-openai ``` -------------------------------- ### Nuxt Configuration Source: https://github.com/arcjet/arcjet-docs/blob/main/src/content/docs/reference/nuxt.mdx Configure Arcjet within your Nuxt application. This example shows basic setup. ```typescript import { defineNuxtConfig } from 'nuxt/config' // https://nuxt.dev/api/configuration/nuxt.config export default defineNuxtConfig({ devtools: { enabled: true }, modules: [ '@arcjet/nuxt' ], arcjet: { // Your Arcjet configuration options here // e.g., siteKey: process.env.ARCJET_SITE_KEY, // secretKey: process.env.ARCJET_SECRET_KEY, } }) ``` -------------------------------- ### Start Next.js App with npm, pnpm, or yarn Source: https://github.com/arcjet/arcjet-docs/blob/main/src/snippets/bot-protection/quick-start/nextjs/Step4.mdx Use your preferred package manager to start the Next.js development server. This command launches the application locally. ```sh npm run dev ``` ```sh pnpm run dev ``` ```sh yarn run dev ``` -------------------------------- ### IP Analysis Example (TypeScript) Source: https://github.com/arcjet/arcjet-docs/blob/main/src/content/docs/reference/nodejs.mdx Demonstrates how to perform IP analysis using the Arcjet SDK in a TypeScript environment. This example shows how to get location and ASN details for a given IP address. ```ts import { Arcjet, protect } from "@arcjet/next"; const arcjet = new Arcjet({ /* ... */ }); export default protect(async (req, res) => { const { ip } = req; const geo = await arcjet.ipAnalysis.lookup(ip); return res.json({ name: `Hello ${geo?.countryName || "World"}!`, // Example: "Hello United States!" ip: geo, }); }); ``` -------------------------------- ### Handle Arcjet Errors in GET Request (JavaScript) Source: https://github.com/arcjet/arcjet-docs/blob/main/tests/llms-txt.test.ts-snapshots/reference-astro-chromium-linux.md This JavaScript example shows how to handle potential Arcjet errors in a GET request. It logs errors and allows requests to proceed, with an option to fail closed. ```javascript import aj from "arcjet:client"; export const GET = async ({ request }) => { const decision = await aj.protect(request); 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 //return Response.json({ error: "Service unavailable" }, { status: 503 }); } } if (decision.isDenied()) { return Response.json( { error: "Too Many Requests" }, { status: 429, }, ); } return Response.json( { message: "Hello world", }, { status: 200, }, ); }; ``` -------------------------------- ### Start Server with TypeScript Source: https://github.com/arcjet/arcjet-docs/blob/main/src/snippets/email-validation/quick-start/nodejs/Step4.mdx Use this command to start your server using TypeScript. Ensure you have Node.js 20+ or a dotenv package for environment variable loading. ```sh npx tsx --env-file .env.local index.ts ``` -------------------------------- ### Install Logging Dependencies Source: https://github.com/arcjet/arcjet-docs/blob/main/src/content/docs/reference/fastify.mdx Install pino and pino-pretty for custom logging with Fastify and Arcjet. ```sh npm install pino pino-pretty ``` ```sh pnpm add pino pino-pretty ``` ```sh yarn add pino pino-pretty ``` -------------------------------- ### Allow non-VPN, US-based GET requests Source: https://github.com/arcjet/arcjet-docs/blob/main/src/content/docs/filters/reference.mdx This example demonstrates how to configure Arcjet to allow requests that are not from a VPN, originate from the US, and are of the GET method. This is a common use case for restricting access based on geographical location and network type. ```javascript import { Arcjet, Filter } from "@arcjet/next"; const arcjet = new Arcjet(); export default async function middleware(request) { return arcjet.protect(request, { filter: new Filter({ // Allow non-VPN, US-based GET requests // See: https://docs.arcjet.com/filters/reference expression: "vpn == false && country_code == 'US' && method == 'GET'", }), }); } ``` -------------------------------- ### Install shadcn Components Source: https://github.com/arcjet/arcjet-docs/blob/main/src/content/docs/blueprints/feedback-form.mdx Installs necessary UI components from shadcn/ui for the feedback form. ```shell npx shadcn@latest add button card input label toast use-toast ``` -------------------------------- ### IP Analysis Configuration (JS - Tab) Source: https://github.com/arcjet/arcjet-docs/blob/main/src/content/docs/reference/astro.mdx JavaScript example for enabling IP analysis within Astro server setup. ```javascript const IPLocationJS = ` import { defineIntegration } from "astro:content"; export const config = defineIntegration({ name: "@arcjet/astro", hooks: { // Example of how to use IP analysis "astro:server:setup": (context) => { context.server.set("arcjet:ip-analysis:enabled", true); }, }, }); `; ``` -------------------------------- ### Log Decision Configuration (JS - Tab) Source: https://github.com/arcjet/arcjet-docs/blob/main/src/content/docs/reference/astro.mdx JavaScript example for logging decision results within Astro server setup. ```javascript const DecisionLogJS = ` import { defineIntegration } from "astro:content"; export const config = defineIntegration({ name: "@arcjet/astro", hooks: { // Example of how to log decision results "astro:server:setup": (context) => { context.server.set("arcjet:log:decision", true); }, }, }); `; ``` -------------------------------- ### Bun: Token bucket request example Source: https://github.com/arcjet/arcjet-docs/blob/main/src/content/docs/rate-limiting/reference.mdx Demonstrates a token bucket rate limit configuration in Bun, specifying the initial token count, window size, and refill rate. ```typescript import { Arcjet, type ArcjetRequest } from "@arcjet/next"; const arcjet = new Arcjet(); export default async function handler(req: ArcjetRequest, res: Response) { const result = await arcjet.protect( (request) => { return request.headers.get("x-user-id"); }, { tokenBucket: { count: 100, // Initial number of tokens window: 60, // Window size in seconds refilRate: 10, // Tokens refilled per second }, } ); if (result.isBlocked) { return new Response("Too many requests", { status: 429, }); } return new Response("Hello, world!"); } ``` -------------------------------- ### Start Bun Application Source: https://github.com/arcjet/arcjet-docs/blob/main/public/llms-full.txt Start the Bun application using the bun run command. ```shell bun run index.ts ``` -------------------------------- ### Handle Arcjet Errors in Astro GET Request (TypeScript) Source: https://github.com/arcjet/arcjet-docs/blob/main/tests/llms-txt.test.ts-snapshots/reference-astro-chromium-linux.md This TypeScript example demonstrates how to handle potential Arcjet errors during request processing in an Astro GET route. It logs errors and fails open by default, but can be configured to fail closed. ```typescript import aj from "arcjet:client"; import type { APIRoute } from "astro"; export const GET: APIRoute = async ({ request }) => { const decision = await aj.protect(request); 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 //return Response.json({ error: "Service unavailable" }, { status: 503 }); } } if (decision.isDenied()) { return Response.json( { error: "Too Many Requests" }, { status: 429, }, ); } return Response.json( { message: "Hello world", }, { status: 200, }, ); }; ``` -------------------------------- ### Python FastAPI Filtering Example Source: https://github.com/arcjet/arcjet-docs/blob/main/src/snippets/bot-protection/reference/python-fastapi/Filtering.mdx This snippet demonstrates a basic request filtering setup in a Python FastAPI application using Arcjet. ```python from fastapi import FastAPI from arcjet import Arcjet, protect app = FastAPI() arcjet = Arcjet(ruleset='my-ruleset') @app.get("/") @protect() def read_root(): return {"message": "Hello World"} @app.get("/items/{item_id}") @protect(ruleset='another-ruleset') def read_item(item_id: int, q: str | None = None): return {"item_id": item_id, "q": q} ``` -------------------------------- ### Start Server with Bun (TypeScript) Source: https://github.com/arcjet/arcjet-docs/blob/main/src/snippets/email-validation/quick-start/bun/Step4.mdx Use this command to start your server in development mode with hot-reloading for TypeScript files. Ensure your main file is named index.ts. ```sh bun run --hot index.ts ``` -------------------------------- ### Install Arcjet SDK Source: https://github.com/arcjet/arcjet-docs/blob/main/src/content/docs/filters/quick-start.mdx Install the Arcjet SDK for your specific framework. This is the first step to integrating Arcjet protection. ```bash npm install @arcjet/astro # or yarn add @arcjet/astro # or pnpm add @arcjet/astro ``` ```bash npm install @arcjet/bun # or yarn add @arcjet/bun # or pnpm add @arcjet/bun ``` ```bash npm install @arcjet/deno # or yarn add @arcjet/deno # or pnpm add @arcjet/deno ``` ```bash npm install @arcjet/fastify # or yarn add @arcjet/fastify # or pnpm add @arcjet/fastify ``` ```bash npm install @arcjet/nest-js # or yarn add @arcjet/nest-js # or pnpm add @arcjet/nest-js ``` ```bash npm install @arcjet/next-js # or yarn add @arcjet/next-js # or pnpm add @arcjet/next-js ``` ```bash npm install @arcjet/node-js # or yarn add @arcjet/node-js # or pnpm add @arcjet/node-js ``` ```bash pip install arcjet-fastapi ``` ```bash pip install arcjet-flask ``` ```bash npm install @arcjet/react-router # or yarn add @arcjet/react-router # or pnpm add @arcjet/react-router ``` ```bash npm install @arcjet/remix # or yarn add @arcjet/remix # or pnpm add @arcjet/remix ``` ```bash npm install @arcjet/sveltekit # or yarn add @arcjet/sveltekit # or pnpm add @arcjet/sveltekit ``` -------------------------------- ### Cloudflare Integration Source: https://github.com/arcjet/arcjet-docs/blob/main/src/content/docs/reference/nextjs.mdx Example configuration for integrating Arcjet with Cloudflare. This setup leverages Cloudflare's edge network for enhanced security. ```typescript import type { ArcjetConfig, ArcjetRule, ArcjetRuleMode, } from "@arcjet/next"; const config: ArcjetConfig = { siteKey: process.env.ARCJET_SITE_KEY!, // Use Cloudflare's IP header to identify clients client: { header: "CF-Connecting-IP", }, rules: [ { type: "rate-limit", window: "1m", count: 100, }, ], }; export default config; ``` -------------------------------- ### Install Arcjet and Flask Source: https://github.com/arcjet/arcjet-docs/blob/main/public/llms-full.txt Install the necessary libraries for Arcjet and Flask. Use uv for faster dependency management if available. ```shell pip install arcjet flask # or with uv: uv add arcjet flask langchain langchain-openai ``` -------------------------------- ### Add Arcjet Filters Source: https://github.com/arcjet/arcjet-docs/blob/main/src/content/docs/filters/quick-start.mdx Integrate Arcjet filters into your application's request handling. This example shows a basic filter setup. ```typescript import { Arcjet } from "@arcjet/next-js"; const arcjet = new Arcjet({ token: process.env.ARCJET_KEY }); export default arcjet.protect((req, res) => { // Your route handler res.send("Hello World!"); }); ``` ```typescript import { Arcjet } from "@arcjet/node-js"; const arcjet = new Arcjet({ token: process.env.ARCJET_KEY }); app.use(arcjet.protect); app.get("/", (req, res) => { res.send("Hello World!"); }); ``` ```typescript import { Arcjet } from "@arcjet/fastify"; const arcjet = new Arcjet({ token: process.env.ARCJET_KEY }); fastify.register(arcjet.protect); fastify.get("/", async () => "Hello World!"); ``` ```typescript import { Arcjet } from "@arcjet/nest-js"; @Module({ imports: [ ArcjetModule.register({ token: process.env.ARCJET_KEY, }), ], controllers: [AppController], providers: [AppService], }) export class AppModule {} ``` ```typescript import { Arcjet } from "@arcjet/astro"; const arcjet = new Arcjet({ token: process.env.ARCJET_KEY }); export const onRequest: API onRequest = async ({ request }) => { return arcjet.protect(request); }; ``` ```typescript import { Arcjet } from "@arcjet/sveltekit"; const arcjet = new Arcjet({ token: process.env.ARCJET_KEY }); export const handle: Handle = async ({ event }) => { return arcjet.protect(event); }; ``` ```typescript import { Arcjet } from "@arcjet/remix"; const arcjet = new Arcjet({ token: process.env.ARCJET_KEY }); export const loader: LoaderFunction = async ({ request }) => { return arcjet.protect(request); }; ``` ```typescript import { Arcjet } from "@arcjet/react-router"; const arcjet = new Arcjet({ token: process.env.ARCJET_KEY }); export const loader: LoaderFunction = async ({ request }) => { return arcjet.protect(request); }; ``` ```python from arcjet.fastapi import ArcjetFastAPI app = ArcjetFastAPI(app, token=os.environ.get("ARCJET_KEY")) ``` ```python from arcjet.flask import ArcjetFlask app = ArcjetFlask(__name__, token=os.environ.get("ARCJET_KEY")) ``` ```typescript import { Arcjet } from "@arcjet/bun"; const arcjet = new Arcjet({ token: process.env.ARCJET_KEY }); const app = Bun.serve({ fetch(req) { return arcjet.protect(req); }, }); ``` ```typescript import { Arcjet } from "@arcjet/deno"; const arcjet = new Arcjet({ token: process.env.ARCJET_KEY }); Deno.serve(async (req) => { return arcjet.protect(req); }); ``` -------------------------------- ### Block Bot Signals in Node.js Source: https://github.com/arcjet/arcjet-docs/blob/main/src/content/docs/bot-protection/advanced-signals.mdx Apply Arcjet's bot signal blocking to your Node.js application. This example demonstrates the setup for Node.js environments. ```typescript import arcjet from "arcjet"; import express from "express"; const app = express(); app.use(arcjet({ /* options */ })); app.get('/', (req, res) => { res.send('Hello World!'); }); app.listen(3000, () => { console.log('Server listening on port 3000'); }); ``` -------------------------------- ### Install Arcjet CLI and Authenticate Source: https://github.com/arcjet/arcjet-docs/blob/main/public/llms-full.txt Install the Arcjet CLI globally and log in to your account to manage sites and retrieve credentials. ```bash npm i -g @arcjet/cli ``` ```bash arcjet auth login ``` -------------------------------- ### Identify Bots in TypeScript Source: https://github.com/arcjet/arcjet-docs/blob/main/src/snippets/bot-protection/reference/nestjs/IdentifiedBots.mdx Example of how to use Arcjet's bot identification features in a TypeScript environment. Ensure you have the necessary Arcjet SDK installed and configured. ```typescript import SelectableContent from "@/components/SelectableContent"; import { Code } from "@astrojs/starlight/components"; import IdentifiedBotsTS from "./IdentifiedBots.ts?raw";
``` -------------------------------- ### Install Arcjet Source: https://github.com/arcjet/arcjet-docs/blob/main/src/content/docs/signup-protection/quick-start.mdx Install the Arcjet SDK for your framework. This is the first step to integrating signup form protection. ```bash npm install @arcjet/next npm install @arcjet/node npm install @arcjet/bun npm install @arcjet/remix npm install @arcjet/sveltekit npm install @arcjet/nestjs npm install @arcjet/python ``` -------------------------------- ### Run Fastify App with TypeScript Source: https://github.com/arcjet/arcjet-docs/blob/main/src/snippets/get-started/fastify/Step4.mdx Use this command to start your Fastify application when using TypeScript. Ensure you have Node.js 24.3.0+ or a package like `tsx` installed. ```sh node --env-file .env.local server.ts ``` -------------------------------- ### Start Server (Python + FastAPI) Source: https://github.com/arcjet/arcjet-docs/blob/main/src/content/docs/rate-limiting/quick-start.mdx Start your Python FastAPI development server using Uvicorn. Ensure the ARCJET_KEY environment variable is set. ```bash uvicorn src.main:app --reload ``` -------------------------------- ### TypeScript Example with Vercel Toolbar Source: https://github.com/arcjet/arcjet-docs/blob/main/src/snippets/nosecone/reference/WithVercelToolbar.mdx This TypeScript code snippet shows how to configure Arcjet when using the Vercel Toolbar. Ensure the Vercel Toolbar is installed and configured in your project. ```ts import { Arcjet } from "@arcjet/next"; const arcjet = new Arcjet(); export default arcjet.protect((req, res) => { // Your Next.js API route logic here res.status(200).json({ message: "Hello, world!" }); }); ``` -------------------------------- ### Start Node.js Server with Bot Protection Source: https://github.com/arcjet/arcjet-docs/blob/main/src/snippets/bot-protection/quick-start/nodejs/Step4.mdx Use this command to start your Node.js server. Ensure your environment variables are loaded correctly using `--env-file`. This command is available for both TypeScript and JavaScript projects. ```typescript npx tsx --env-file .env.local index.ts ``` ```javascript node --env-file .env.local index.js ``` -------------------------------- ### Arcjet Initialization and Rate Limiting Source: https://github.com/arcjet/arcjet-docs/blob/main/tests/llms-txt.test.ts-snapshots/reference-remix-chromium-linux.md Demonstrates how to initialize Arcjet with a site key and configure a token bucket rate limit rule. It also shows how to protect Remix loader functions. ```APIDOC ## Initialize Arcjet ```javascript import arcjet, { tokenBucket } from "@arcjet/remix"; const aj = arcjet({ key: process.env.ARCJET_KEY, rules: [ tokenBucket({ mode: "LIVE", // or "DRY_RUN" characteristics: ["userId"], refillRate: 5, interval: 10, capacity: 10, }), ], }); ``` ### Description Initializes the Arcjet SDK with your site key and defines a rate limiting rule using the token bucket algorithm. The `mode` can be set to `"LIVE"` to enforce limits or `"DRY_RUN"` to only log violations. The `characteristics` define how requests are tracked (e.g., by `userId`). `refillRate`, `interval`, and `capacity` configure the token bucket's behavior. ## Protect Remix Loader Function ```javascript export async function loader(args) { const userId = "user123"; // Replace with your authenticated user ID const decision = await aj.protect(args, { userId, requested: 5 }); if (decision.isDenied()) { throw new Response("Forbidden", { status: 403, statusText: "Forbidden" }); } return null; } ``` ### Description Protects a Remix loader function by calling `aj.protect()`. This function takes the loader arguments and an optional object containing characteristics like `userId` and the number of tokens `requested`. If the `decision` is denied, a `403 Forbidden` response is thrown. Otherwise, the request proceeds. ``` -------------------------------- ### Test Sending Personal Info Source: https://github.com/arcjet/arcjet-docs/blob/main/src/content/docs/sensitive-info/quick-start.mdx Start your app and make a request with an email address in the body to test sensitive info detection. This example shows a typical request. ```bash curl -X POST -H "Content-Type: application/json" -d '{"email": "test@example.com"}' http://localhost:3000 ``` -------------------------------- ### Start Server (Python + Flask) Source: https://github.com/arcjet/arcjet-docs/blob/main/src/content/docs/rate-limiting/quick-start.mdx Start your Python Flask development server. Ensure the ARCJET_KEY environment variable is set. ```bash flask --app src/app.py run --debug ``` -------------------------------- ### Serve Bun Application with Arcjet Source: https://github.com/arcjet/arcjet-docs/blob/main/src/content/docs/reference/bun.mdx Example of serving a Bun application with Arcjet integrated. This snippet shows a basic setup for a Bun server that uses Arcjet for protection. ```typescript import Arcjet from "@arcjet/bun"; const arcjet = new Arcjet( "YOUR_SITE_DETAILS", "YOUR_API_KEY" ); // Example using Bun's built-in server Bun.serve({ fetch: async (req) => { const protectedReq = await arcjet.protect(req); return new Response("Hello Arcjet!"); }, port: 3000, }); console.log("Server running on http://localhost:3000"); ``` -------------------------------- ### Start Flask Development Server Source: https://github.com/arcjet/arcjet-docs/blob/main/src/snippets/bot-protection/quick-start/python-flask/Step4.mdx Run the Flask development server with debugging enabled. Ensure your application is correctly configured before starting. ```bash uv run flask --app main run --debug ``` -------------------------------- ### Arcjet Initialization and Usage Source: https://github.com/arcjet/arcjet-docs/blob/main/tests/llms-txt.test.ts-snapshots/reference-remix-chromium-darwin.md Demonstrates how to initialize the Arcjet SDK with a site key and rate limiting rules, and how to protect requests using the `protect` function within a Remix loader. ```APIDOC ## Initialize Arcjet ```javascript import arcjet, { tokenBucket } from "@arcjet/remix"; const aj = arcjet({ key: process.env.ARCJET_KEY, rules: [ tokenBucket({ mode: "LIVE", characteristics: ["userId"], refillRate: 5, interval: 10, capacity: 10, }), ], }); ``` ### Description Initializes the Arcjet SDK with your site key and defines a token bucket rate limiting rule. The `mode` can be set to `"LIVE"` to enforce limits or `"DRY_RUN"` to only log. ### Parameters - **key** (string) - Your Arcjet site key, typically retrieved from environment variables. - **rules** (Array) - An array of rule configurations. The example uses `tokenBucket`. - **mode** (string) - `"LIVE"` or `"DRY_RUN"`. - **characteristics** (Array) - Identifiers to track requests by (e.g., `"userId"`). - **refillRate** (number) - Tokens to refill per interval. - **interval** (number) - The time interval in seconds for refilling tokens. - **capacity** (number) - The maximum number of tokens the bucket can hold. ## Protect Request in Remix Loader ```javascript export async function loader(args) { const userId = "user123"; // Replace with your authenticated user ID const decision = await aj.protect(args, { userId, requested: 5 }); if (decision.isDenied()) { throw new Response("Forbidden", { status: 403, statusText: "Forbidden" }); } return null; } ``` ### Description Protects incoming requests within a Remix loader function. It uses the initialized Arcjet instance to evaluate rules and decides whether to allow or deny the request. ### Method `aj.protect(args, options)` ### Parameters - **args** (object) - The arguments passed to the Remix loader function. - **options** (object) - **userId** (string) - The identifier for the current user, required if specified in rule characteristics. - **requested** (number) - The number of tokens to deduct for this request. ### Response - **ArcjetDecision** - An object containing the decision details. - **isDenied()** (`bool`) - Returns `true` if the request is denied. ### Error Handling - Throws a `Response` with status 403 if `decision.isDenied()` is true. ``` -------------------------------- ### JavaScript Pages Router Route Source: https://github.com/arcjet/arcjet-docs/blob/main/src/snippets/sensitive-info/reference/nextjs/PerRoute.mdx Example of configuring Arcjet for a specific route using JavaScript within the Next.js Pages Router. This is the JavaScript equivalent for the Pages Router setup. ```javascript import { Arcjet, protect } from "@arcjet/next"; const arcjet = Arcjet.fromEnv(); export default protect(arcjet, async (req, res) => { // Your route logic here res.status(200).send("Hello, world!"); }); ```