agentleFS
CloudflareKnown publishercloudflare/templates/x402-proxy-template/AGENTS.md

templates / x402-proxy-template

AGENTS.md2.1k starsChanged 11 months agoMITView on GitHub

Context for AI coding agents to help users set up x402-proxy for payment-gated content. A Cloudflare Worker that adds payment gating to any origin using the x402 protocol. Users pay to access protected routes, then get a JWT cookie valid for 1 hour. With Bot Management Filtering: Requires Bot Management for Enterprise to enable bot filtering. With it enabled, x402-proxy can implement "default closed" - humans pass through free, only bots must pay. This is optional and enhances the base…

Trending

Quiet this year.thin dataabout the whole repository

Dec 2025: 0 mentionsJan 2026: 0 mentionsFeb 2026: 0 mentionsMar 2026: 0 mentionsApr 2026: 0 mentionsMay 2026: 0 mentionsJun 2026: 0 mentionsJul 2026: 0 mentionsAug 2026: 0 mentionsSep 2026: 0 mentionsOct 2026: 0 mentionsNov 2026: 0 mentions
Dec 2025Jun 2026Nov 2026
Mentions a month of the cloudflare/templates repository that our weekly crawl found: only 5 in all, so this is a hint, not a trend. There is no adoption data for this file yet.
  • Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about checking a change actually works.

    Of the AGENTS.md files we read, the 11,773 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.

  • In this repository4 other files it gives its agents.

The file

Show its rules and text

We split this AGENTS.md into the rules it gives an agent

39 rules. About 0 are common, 23 are distinctive, and 16 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈23

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 16

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    When a user asks for help setting up x402-proxy, follow this discovery process:

    line 15
  2. Very specific:

    If not logged in, guide them to run npx wrangler login.

    line 23
  3. Distinctive:

    If they have multiple accounts, note them for Step 2.

    line 25
  4. Distinctive:

    Ask: "Which domain do you want to add payment gating to?"

    line 31
  5. Distinctive:

    If the user has multiple Cloudflare accounts (from Step 1), also ask: "Which account is this domain on?"

    line 33
  6. Very specific:

    Ask: "Do you have Bot Management enabled on {domain}?"

    line 41
  7. Very specific:

    Ask: "What path on {domain} do you want to charge for?"

    line 58
  8. Distinctive:

    If the user provides multiple paths at once, queue them and configure each in sequence.

    line 60
  9. Very specific:

    Ask: "What price (in USD) for {path}?"

    line 66
  10. Very specific:

    Ask: "What description for {path}?" (shown to users explaining what they're paying for)

    line 72
  11. Very specific:

    Ask: "What bot score threshold for {path}?"

    line 84
  12. Very specific:

    Ask: "Any bots that should get FREE access to {path}?"

    line 98
  13. Distinctive:

    If the user selects a preset or names specific bots:

    line 108
  14. Distinctive:

    Look up each bot name in the Bot Registry (see below)

    line 110
  15. Distinctive:

    Write to config with inline comments

    line 112
  16. Very specific:

    Ask: "Any more paths on {domain} to protect?"

    line 131
  17. Distinctive:

    If yes → repeat Step 4 for the next path

    line 133
  18. Distinctive:

    If no → continue to Step 5

    line 134
  19. Distinctive:

    If another worker owns routes on the target domain

    line 172
  20. Distinctive:

    All traffic flows through x402-proxy

    line 275
  21. Distinctive:

    No code changes needed to the existing worker/service

    line 286
  22. Very specific:

    Setup: Add ORIGIN_URL to vars:

    line 293
  23. Distinctive:

    Setup: Add services binding:

    line 310
  24. Distinctive:

    When configuring bot exceptions, use this registry to resolve bot names to detection IDs.

    line 356
  25. Distinctive:

    If a bot isn't in the registry, the user can find its detection ID in the dashboard:

    line 421
  26. Distinctive:

    When switching between modes, you may encounter route ownership conflicts.

    line 483
  27. Distinctive:

    Via wrangler.jsonc: Remove the route from the old worker's config and redeploy.

    line 493
  28. Distinctive:

    Delete route from old worker

    line 506
  29. Distinctive:

    Remove the route from the existing worker (see Route Migration)

    line 520
  30. Very specific:

    Alternative: Use External Origin Mode instead - keep the existing worker's route and set ORIGIN_URL to its workers.dev URL.

    line 523
  31. Distinctive:

    Use Service Binding Mode instead

    line 536
  32. Distinctive:

    Ensure DNS records point to a real origin server (orange cloud enabled)

    line 537
  33. Distinctive:

    DNS Proxy: Check DNS records point to origin, domain is proxied (orange cloud)

    line 541
  34. Very specific:

    External URL: Check ORIGIN_URL is correct and accessible

    line 542
  35. Very specific:

    Service Binding: Check Worker name in services config matches deployed Worker

    line 543
  36. Very specific:

    Must be HTTPS (cookies have Secure flag)

    line 554
  37. Very specific:

    Check SameSite=Strict compatibility with your frontend

    line 555
  38. Very specific:

    Use npx wrangler tail to see bot scores in logs after deployment.

    line 598
  39. Very specific:

    Before running npm run deploy, verify:

    line 619

≈ “Common” is an estimate: at least 1 in 5 of the 16,595 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
AGENTS.md

x402-proxy Setup Guide for AI Agents

Context for AI coding agents to help users set up x402-proxy for payment-gated content.

What is x402-proxy?

A Cloudflare Worker that adds payment gating to any origin using the x402 protocol. Users pay to access protected routes, then get a JWT cookie valid for 1 hour.

With Bot Management Filtering: Requires Bot Management for Enterprise to enable bot filtering. With it enabled, x402-proxy can implement "default closed" - humans pass through free, only bots must pay. This is optional and enhances the base functionality.


Interactive Setup Flow

When a user asks for help setting up x402-proxy, follow this discovery process:

Step 1: Verify Cloudflare Authentication

npx wrangler whoami

If not logged in, guide them to run npx wrangler login.

If they have multiple accounts, note them for Step 2.


Step 2: Select Domain

Ask: "Which domain do you want to add payment gating to?"

If the user has multiple Cloudflare accounts (from Step 1), also ask: "Which account is this domain on?"

Save the domain - it scopes everything that follows.


Step 3: Check for Bot Management (Optional Enhancement)

Ask: "Do you have Bot Management enabled on {domain}?"

Explain why you're asking:

With Bot Management, x402-proxy can implement "default closed" - blocking bot traffic by score threshold while letting humans through automatically. You can also make specific exceptions for bots like Googlebot or verified AI crawlers.

Without Bot Management, x402-proxy still works perfectly - it just charges for protected routes without distinguishing between bots and humans. All traffic to protected routes must pay.

AnswerEffect
YesEnable Bot Management Filtering prompts in Step 4
NoSkip threshold/exception prompts in Step 4

Step 4: Configure Protected Paths (Iterative)

Ask: "What path on {domain} do you want to charge for?"

If the user provides multiple paths at once, queue them and configure each in sequence.

For EACH path, ask:

4.1 Price

Ask: "What price (in USD) for {path}?"

Format: $0.01, $0.10, $1.00, etc.

4.2 Description

Ask: "What description for {path}?" (shown to users explaining what they're paying for)

Example: "Access to premium content for 1 hour"


If User Has Bot Management (from Step 3):

Continue with these additional prompts:

4.3 Bot Score Threshold

Ask: "What bot score threshold for {path}?"

ALWAYS offer exactly these three options:

OptionThresholdWhat it means
11Very strict - only verified humans pass free
22Strict - only clear human traffic passes free
30 (Recommended)30Balanced - likely automated traffic must pay, humans pass free

Recommended: 30 - This is the typical starting point that blocks likely-automated traffic while letting humans through free.

4.4 Bot Exceptions

Ask: "Any bots that should get FREE access to {path}?"

Offer these preset options:

PresetBots IncludedUse When
Googlebot + BingBotGooglebot, BingBotAllow major crawlers
Above + AI assistantsAbove + ChatGPT-User, Claude-User, Perplexity-User, Meta-ExternalFetcherAllow AI assistant citations
None(empty)All bots must pay

If the user selects a preset or names specific bots:

  1. Look up each bot name in the Bot Registry (see below)
  2. Resolve to detection IDs
  3. Write to config with inline comments

Example resolution:

  • User says: "Googlebot and BingBot"
  • Agent looks up: Googlebot → 120623194, BingBot → 117479730
  • Config output:
"except_detection_ids": [
  120623194,  // Googlebot
  117479730   // BingBot
]

After Configuring Each Path

Ask: "Any more paths on {domain} to protect?"

  • If yes → repeat Step 4 for the next path
  • If no → continue to Step 5

Step 5: Wallet & Network Configuration

Ask these together:

  1. "What wallet address should receive payments (PAY_TO)?"
  2. "Which network: base-sepolia (testing) or base (production)?"

If User Doesn't Have a Wallet Address

They can use the default "dead address" for testing: 0x000000000000000000000000000000000000dEaD

For production, they'll need a real wallet:


Deployment Phase

Now that configuration is complete, discover infrastructure and deploy.

Step 6: Discover Existing Workers & Routes

npx wrangler deployments list
npx wrangler routes list --zone {domain}

This reveals:

  • What workers are already deployed
  • If another worker owns routes on the target domain

Determine deployment mode:

SituationRecommended Mode
Origin is traditional server (VM/container)Standard Proxy Mode
Origin is external API or serviceExternal Origin Mode
Origin is another Worker in your accountService Binding Mode
Existing worker owns domain/*External Origin Mode*

*For existing workers with source code available, you can use Service Binding Mode for better performance.


Step 7: Generate wrangler.jsonc

Based on gathered information, generate the complete configuration.

Example - Basic (no Bot Management Filtering):

{
	"routes": [
		{ "pattern": "example.com/premium/*", "zone_name": "example.com" },
	],
	"vars": {
		"PAY_TO": "0x000000000000000000000000000000000000dEaD",
		"NETWORK": "base-sepolia",
		"PROTECTED_PATTERNS": [
			{
				"pattern": "/premium/*",
				"price": "$0.10",
				"description": "Access to premium content for 1 hour",
			},
		],
	},
}

Example - With Bot Management Filtering:

Requires Bot Management for Enterprise to enable bot filtering.

{
	"routes": [
		{ "pattern": "example.com/premium/*", "zone_name": "example.com" },
	],
	"vars": {
		"PAY_TO": "0x000000000000000000000000000000000000dEaD",
		"NETWORK": "base-sepolia",
		"PROTECTED_PATTERNS": [
			{
				"pattern": "/premium/*",
				"price": "$0.10",
				"description": "Access to premium content for 1 hour",
				"bot_score_threshold": 30,
				"except_detection_ids": [
					120623194, // Googlebot
					117479730, // BingBot
				],
			},
		],
	},
}

Step 8: Set JWT Secret

node -e "console.log(require('crypto').randomBytes(32).toString('hex'))" | npx wrangler secret put JWT_SECRET

Step 9: Deploy

npm run deploy

Step 10: Verify

curl https://{domain}/__x402/health
# Should return: {"status":"ok","timestamp":...}

curl https://{domain}/__x402/config
# Should show protected patterns and Bot Management Filtering status

Deployment Modes

Standard Proxy Mode (DNS-Based)

  • x402-proxy owns the route (e.g., api.example.com/*)
  • All traffic flows through x402-proxy
  • Protected paths require payment, others pass through to DNS origin
  • Use when: Origin is a traditional server (VM, container) with DNS pointing to it
User → x402-proxy (owns route) → Origin Server (via Cloudflare DNS)

External Origin Mode

  • x402-proxy owns the route and proxies to an external URL
  • No code changes needed to the existing worker/service
  • Use when: Origin is an external API, or an existing worker you don't want to modify
User → x402-proxy (owns route) → External Service (via ORIGIN_URL)

Setup: Add ORIGIN_URL to vars:

"ORIGIN_URL": "https://my-existing-worker.myaccount.workers.dev"

Service Binding Mode

  • x402-proxy calls the origin worker directly via Service Binding
  • Zero network overhead - both workers run on the same thread
  • Origin worker doesn't need a public route
  • Use when: Origin is another Worker in your account and you want optimal performance
User → x402-proxy (owns route) → Origin Worker (via Service Binding)

Setup: Add services binding:

"services": [{ "binding": "ORIGIN_SERVICE", "service": "my-origin-worker" }]

Bot Management Filtering Reference

Requires Bot Management for Enterprise to enable bot filtering. When enabled, users can configure payment exemptions based on bot score and detection IDs.

How It Works

Request arrives at protected route
         │
         ▼
    Bot Management Filtering configured?
    ┌────────┴────────┐
   No                Yes
    │                 │
    ▼                 ▼
 All traffic    Check bot score & exceptions
 must pay            │
                ┌────┴────┐
                │         │
           Human OR    Bot (not excepted)
           Excepted Bot     │
                │           ▼
                ▼      Check cookie/payment
           Pass FREE        │
           to origin   Valid? → Proxy + set cookie
                       Invalid? → Return 402

Bot Score Threshold Reference

ThresholdMeaningUse Case
1Very strict - only verified humans pass freeMaximum monetization
2Strict - only clear human traffic passes freeHigh-value APIs
30Balanced - likely automated must pay, humans pass freeRecommended - typical starting point

Bot Registry Reference

When configuring bot exceptions, use this registry to resolve bot names to detection IDs.

Included operators: Google, Microsoft, OpenAI, Anthropic, Perplexity, Meta

For additional bots, users can find detection IDs in the Cloudflare dashboard: AI Crawl Control → Crawlers → Actions menu → Copy detection ID

Google

Bot NameDetection IDNotes
Googlebot120623194Google Search
Google-CloudVertexBot133730073Google AI training

Microsoft

Bot NameDetection IDNotes
BingBot117479730Microsoft Bing

OpenAI

Bot NameDetection IDNotes
GPTBot123815556OpenAI training
ChatGPT-User132995013ChatGPT browsing mode
ChatGPT agent129220581ChatGPT agents/plugins
OAI-SearchBot126255384OpenAI SearchGPT

Anthropic (Heuristics IDs)

Bot NameHeuristics IDNotes
ClaudeBot33563859Anthropic training
Claude-SearchBot33564301Anthropic search
Claude-User33564303Claude web access

Perplexity (Heuristics IDs)

Bot NameHeuristics IDNotes
PerplexityBot33563889Perplexity search
Perplexity-User33564371Perplexity answers

Meta

Bot NameDetection IDNotes
Meta-ExternalAgent124581738Meta AI training
Meta-ExternalFetcher132272919Meta AI assistant
FacebookBot(heuristics: 33563972)Meta crawling

Example Preset

"except_detection_ids": [
  120623194,  // Googlebot
  117479730,  // BingBot
  132995013,  // ChatGPT-User
  33564303    // Claude-User
]

Finding Custom Detection IDs

If a bot isn't in the registry, the user can find its detection ID in the dashboard:

  1. Go to AI Crawl Control in Cloudflare dashboard
  2. Navigate to Crawlers
  3. Find the crawler in the list
  4. Click the three dot menu in the Actions column
  5. Copy the detection ID

Configuration Reference

Required Variables

VariableDescription
PAY_TOWallet address to receive payments
NETWORK"base-sepolia" (test) or "base" (production)
JWT_SECRETSecret for signing tokens (64 hex chars)
PROTECTED_PATTERNSArray of protected route configurations

Protected Pattern Schema

{
  pattern: string;              // Route to protect (e.g., "/premium/*")
  price: string;                // Price in USD (e.g., "$0.01")
  description: string;          // Shown to users
  // Bot Management Filtering (optional)
  bot_score_threshold?: number; // 1, 2, or 30
  except_detection_ids?: number[]; // Bot detection IDs to allow free
}

Optional Variables

VariableDescription
ORIGIN_URLExternal URL to proxy to (for External Origin Mode)
ORIGIN_SERVICEService Binding to origin Worker
FACILITATOR_URLPayment facilitator (defaults to CDP)

Debug Endpoints

  • /__x402/health - Health check
  • /__x402/config - Current config (no secrets exposed, shows Bot Management Filtering status)
  • /__x402/protected - Test payment flow ($0.01)

Origin Auto-Detection

x402-proxy automatically detects how to reach the origin:

PriorityConfig PresentHow it works
1ORIGIN_SERVICE bindingCalls bound Worker directly
2ORIGIN_URL setRewrites URL to that origin
3NeitherUses fetch() via Cloudflare DNS

Route Migration

When switching between modes, you may encounter route ownership conflicts.

Understanding Route Ownership

  • Routes can only be owned by one worker at a time
  • A route must be deleted from the old worker before the new worker can claim it
  • Custom domains and routes are different mechanisms (check which one your worker uses)

Migrating Routes Between Workers

Via wrangler.jsonc: Remove the route from the old worker's config and redeploy.

Via Dashboard:

  1. Go to Workers & Pages → your worker
  2. Click "Triggers" tab
  3. Remove the route

See Workers Routes documentation for more details.

Order of Operations to Minimize Downtime

  1. Deploy new worker (without routes) and verify it works via workers.dev
  2. Delete route from old worker
  3. Immediately redeploy new worker with routes

Common Issues

"A route with the same pattern already exists" [code: 10020]

Another worker owns this route. You must delete the route from that worker first, then redeploy.

To fix:

  1. Identify which worker owns the route: npx wrangler routes list --zone <domain>
  2. Remove the route from the existing worker (see Route Migration)
  3. Redeploy x402-proxy with that route

Alternative: Use External Origin Mode instead - keep the existing worker's route and set ORIGIN_URL to its workers.dev URL.

"Connection timed out" (522) after deploying

x402-proxy is intercepting traffic but has no origin to proxy to. This happens when:

  • ORIGIN_URL is not set and there's no DNS origin
  • The origin server is not reachable
  • You're using routes without configuring an origin

To fix:

  • Set ORIGIN_URL to point to an actual backend
  • Use Service Binding Mode instead
  • Ensure DNS records point to a real origin server (orange cloud enabled)

Origin not reachable

  • DNS Proxy: Check DNS records point to origin, domain is proxied (orange cloud)
  • External URL: Check ORIGIN_URL is correct and accessible
  • Service Binding: Check Worker name in services config matches deployed Worker

Payment works but content fails

The origin is the problem, not x402-proxy. Test origin directly:

  • For External Origin: curl https://my-worker.myaccount.workers.dev/path
  • For DNS Proxy: Check your origin server logs

Cookies not persisting

  • Must be HTTPS (cookies have Secure flag)
  • Check SameSite=Strict compatibility with your frontend
  • Cookies are valid for 1 hour after payment

"JWT_SECRET not set" (500) on protected routes

The secret wasn't configured. Run:

node -e "console.log(require('crypto').randomBytes(32).toString('hex'))" | npx wrangler secret put JWT_SECRET

Homepage shows x402 landing page instead of origin content

The template includes static assets in the public/ directory for standalone demos. When proxying to an origin, these must be disabled.

Fix: Comment out or remove the assets configuration in wrangler.jsonc:

// "assets": { "directory": "public" },

Bot Management Filtering: "cf.botManagement not available"

This warning appears in logs when Bot Management Filtering is configured but Bot Management data isn't present in the request.

Causes:

  • Bot Management for Enterprise is not enabled
  • Request is from local development (Bot Management not available locally)

Fix:

  • Enable Bot Management for Enterprise in the Cloudflare dashboard
  • For local testing, the warning is expected - filtering will work after deployment

Bot Management Filtering: Humans still getting 402

Check that:

  1. bot_score_threshold is set (e.g., 30)
  2. The request actually has a bot score > threshold
  3. Bot Management for Enterprise is enabled

Use npx wrangler tail to see bot scores in logs after deployment.


Testing Locally

cp .dev.vars.example .dev.vars
node -e "console.log('JWT_SECRET=' + require('crypto').randomBytes(32).toString('hex'))" >> .dev.vars
npm run dev

curl http://localhost:8787/__x402/health      # Should return 200
curl http://localhost:8787/__x402/protected   # Should return 402

Note: Bot Management data is not available in local development. Bot Management Filtering will only work after deployment to Cloudflare.


Pre-Deploy Checklist

Before running npm run deploy, verify:

  • account_id set in wrangler.jsonc (required if user has multiple Cloudflare accounts)
  • assets configuration commented out or removed (required when proxying to an origin)
  • Origin worker name is correct in services config (for Service Binding mode)
  • JWT_SECRET has been created via npx wrangler secret put JWT_SECRET
  • PROTECTED_PATTERNS configured with correct paths and prices
  • routes configured with correct pattern and zone_name

If using Bot Management Filtering:

  • Bot Management for Enterprise is enabled
  • bot_score_threshold is set on relevant patterns (typically 30)
  • except_detection_ids are resolved from bot names

Additional Resources

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.