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
Who's talking about cloudflare/templates
- cloudflare/workers-sdk“Vite plugin has race condition with HMR - `A hanging Promise was canceled.`”GitHub · Jun 6, 2025 · 13 reactions
- cloudflare/workers-sdk“Container builds incompatible with podman”GitHub · Jun 26, 2025 · 12 reactions
- cloudflare/workerd“Switch to hard tabs for indentation”GitHub · Sep 27, 2022 · 7 reactions
- cloudflare/ai-utils“Switch to hard tabs for indentation”GitHub · Jun 27, 2024 · 3 reactions
- tursodatabase/libsql-client-ts“Cloudflare worker error with opennextjs-cloudflare”GitHub · Mar 18, 2025 · 2 reactions
The biggest 5 of 5 mentions linking to the repository that our crawl found. Each line is their own headline.
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.
- AGENTS.mdAGENTS.md
- agent-visibility-template/AGENTS.mdAGENTS.md
- ai-brand-visibility-template/AGENTS.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
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
- Distinctive: line 15
When a user asks for help setting up x402-proxy, follow this discovery process:
- Very specific: line 23
If not logged in, guide them to run npx wrangler login.
- Distinctive: line 25
If they have multiple accounts, note them for Step 2.
- Distinctive: line 31
Ask: "Which domain do you want to add payment gating to?"
- Distinctive: line 33
If the user has multiple Cloudflare accounts (from Step 1), also ask: "Which account is this domain on?"
- Very specific: line 41
Ask: "Do you have Bot Management enabled on {domain}?"
- Very specific: line 58
Ask: "What path on {domain} do you want to charge for?"
- Distinctive: line 60
If the user provides multiple paths at once, queue them and configure each in sequence.
- Very specific: line 66
Ask: "What price (in USD) for {path}?"
- Very specific: line 72
Ask: "What description for {path}?" (shown to users explaining what they're paying for)
- Very specific: line 84
Ask: "What bot score threshold for {path}?"
- Very specific: line 98
Ask: "Any bots that should get FREE access to {path}?"
- Distinctive: line 108
If the user selects a preset or names specific bots:
- Distinctive: line 110
Look up each bot name in the Bot Registry (see below)
- Distinctive: line 112
Write to config with inline comments
- Very specific: line 131
Ask: "Any more paths on {domain} to protect?"
- Distinctive: line 133
If yes → repeat Step 4 for the next path
- Distinctive: line 134
If no → continue to Step 5
- Distinctive: line 172
If another worker owns routes on the target domain
- Distinctive: line 275
All traffic flows through x402-proxy
- Distinctive: line 286
No code changes needed to the existing worker/service
- Very specific: line 293
Setup: Add ORIGIN_URL to vars:
- Distinctive: line 310
Setup: Add services binding:
- Distinctive: line 356
When configuring bot exceptions, use this registry to resolve bot names to detection IDs.
- Distinctive: line 421
If a bot isn't in the registry, the user can find its detection ID in the dashboard:
- Distinctive: line 483
When switching between modes, you may encounter route ownership conflicts.
- Distinctive: line 493
Via wrangler.jsonc: Remove the route from the old worker's config and redeploy.
- Distinctive: line 506
Delete route from old worker
- Distinctive: line 520
Remove the route from the existing worker (see Route Migration)
- Very specific: line 523
Alternative: Use External Origin Mode instead - keep the existing worker's route and set ORIGIN_URL to its workers.dev URL.
- Distinctive: line 536
Use Service Binding Mode instead
- Distinctive: line 537
Ensure DNS records point to a real origin server (orange cloud enabled)
- Distinctive: line 541
DNS Proxy: Check DNS records point to origin, domain is proxied (orange cloud)
- Very specific: line 542
External URL: Check ORIGIN_URL is correct and accessible
- Very specific: line 543
Service Binding: Check Worker name in services config matches deployed Worker
- Very specific: line 554
Must be HTTPS (cookies have Secure flag)
- Very specific: line 555
Check SameSite=Strict compatibility with your frontend
- Very specific: line 598
Use npx wrangler tail to see bot scores in logs after deployment.
- Very specific: line 619
Before running npm run deploy, verify:
≈ “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.
Files
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 whoamiIf 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.
| Answer | Effect |
| Yes | Enable Bot Management Filtering prompts in Step 4 |
| No | Skip 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:
| Option | Threshold | What it means |
| 1 | 1 | Very strict - only verified humans pass free |
| 2 | 2 | Strict - only clear human traffic passes free |
| 30 (Recommended) | 30 | Balanced - 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:
| Preset | Bots Included | Use When |
| Googlebot + BingBot | Googlebot, BingBot | Allow major crawlers |
| Above + AI assistants | Above + ChatGPT-User, Claude-User, Perplexity-User, Meta-ExternalFetcher | Allow AI assistant citations |
| None | (empty) | All bots must pay |
If the user selects a preset or names specific bots:
- Look up each bot name in the Bot Registry (see below)
- Resolve to detection IDs
- 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:
- "What wallet address should receive payments (PAY_TO)?"
- "Which network:
base-sepolia(testing) orbase(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:
| Situation | Recommended Mode |
| Origin is traditional server (VM/container) | Standard Proxy Mode |
| Origin is external API or service | External Origin Mode |
| Origin is another Worker in your account | Service 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_SECRETStep 9: Deploy
npm run deployStep 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 statusDeployment 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 402Bot Score Threshold Reference
| Threshold | Meaning | Use Case |
| 1 | Very strict - only verified humans pass free | Maximum monetization |
| 2 | Strict - only clear human traffic passes free | High-value APIs |
| 30 | Balanced - likely automated must pay, humans pass free | Recommended - 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
| Bot Name | Detection ID | Notes |
| Googlebot | 120623194 | Google Search |
| Google-CloudVertexBot | 133730073 | Google AI training |
Microsoft
| Bot Name | Detection ID | Notes |
| BingBot | 117479730 | Microsoft Bing |
OpenAI
| Bot Name | Detection ID | Notes |
| GPTBot | 123815556 | OpenAI training |
| ChatGPT-User | 132995013 | ChatGPT browsing mode |
| ChatGPT agent | 129220581 | ChatGPT agents/plugins |
| OAI-SearchBot | 126255384 | OpenAI SearchGPT |
Anthropic (Heuristics IDs)
| Bot Name | Heuristics ID | Notes |
| ClaudeBot | 33563859 | Anthropic training |
| Claude-SearchBot | 33564301 | Anthropic search |
| Claude-User | 33564303 | Claude web access |
Perplexity (Heuristics IDs)
| Bot Name | Heuristics ID | Notes |
| PerplexityBot | 33563889 | Perplexity search |
| Perplexity-User | 33564371 | Perplexity answers |
Meta
| Bot Name | Detection ID | Notes |
| Meta-ExternalAgent | 124581738 | Meta AI training |
| Meta-ExternalFetcher | 132272919 | Meta 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:
- Go to AI Crawl Control in Cloudflare dashboard
- Navigate to Crawlers
- Find the crawler in the list
- Click the three dot menu in the Actions column
- Copy the detection ID
Configuration Reference
Required Variables
| Variable | Description |
PAY_TO | Wallet address to receive payments |
NETWORK | "base-sepolia" (test) or "base" (production) |
JWT_SECRET | Secret for signing tokens (64 hex chars) |
PROTECTED_PATTERNS | Array 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
| Variable | Description |
ORIGIN_URL | External URL to proxy to (for External Origin Mode) |
ORIGIN_SERVICE | Service Binding to origin Worker |
FACILITATOR_URL | Payment 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:
| Priority | Config Present | How it works |
| 1 | ORIGIN_SERVICE binding | Calls bound Worker directly |
| 2 | ORIGIN_URL set | Rewrites URL to that origin |
| 3 | Neither | Uses 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:
- Go to Workers & Pages → your worker
- Click "Triggers" tab
- Remove the route
See Workers Routes documentation for more details.
Order of Operations to Minimize Downtime
- Deploy new worker (without routes) and verify it works via
workers.dev - Delete route from old worker
- 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:
- Identify which worker owns the route:
npx wrangler routes list --zone <domain> - Remove the route from the existing worker (see Route Migration)
- 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_URLis 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_URLto 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_URLis correct and accessible - Service Binding: Check Worker name in
servicesconfig 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
Secureflag) - Check
SameSite=Strictcompatibility 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_SECRETHomepage 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:
bot_score_thresholdis set (e.g., 30)- The request actually has a bot score > threshold
- 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 402Note: 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_idset in wrangler.jsonc (required if user has multiple Cloudflare accounts)assetsconfiguration commented out or removed (required when proxying to an origin)- Origin worker name is correct in
servicesconfig (for Service Binding mode) JWT_SECREThas been created vianpx wrangler secret put JWT_SECRETPROTECTED_PATTERNSconfigured with correct paths and pricesroutesconfigured with correct pattern and zone_name
If using Bot Management Filtering:
- Bot Management for Enterprise is enabled
bot_score_thresholdis set on relevant patterns (typically 30)except_detection_idsare resolved from bot names
Additional Resources
- Workers Routes - Route configuration and management
- Service Bindings - Worker-to-Worker communication
- Custom Domains - Alternative to routes
- Wrangler Commands - CLI reference for discovery
- x402 Protocol - Payment protocol specification
- Bot Management - Cloudflare Bot Management documentation
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
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.

