A Cloudflare Worker that implements payment-gated access to R2 resources using the x402 protocol.
- Payment verification using USDC before granting access to R2 resources
- Configurable pricing (default: $0.10 USDC)
- Support for Base L2 (default) and Radius testnet networks
- Flexible path protection (default: all files)
- Simple drop-in solution for protecting R2 buckets
- Install dependencies:
npm install- Copy the example
wrangler.tomlfile:
cp wrangler.toml.example wrangler.toml- Configure your R2 bucket in
wrangler.toml:
[[r2_buckets]]
binding = "R2_BUCKET"
bucket_name = "your-actual-bucket-name"- Set environment variables:
# Required: Payment address where users send USDC
wrangler secret put PAYMENT_ADDRESS
# Optional configuration (defaults shown)
wrangler secret put PRICE_USDC # Default: "0.10"
wrangler secret put NETWORK_RPC # Default: "https://mainnet.base.org"
wrangler secret put PROTECTED_PATHS # Default: "/*"- Ethereum mainnet:
https://mainnet.infura.io/v3/YOUR_KEY - Base L2 (default):
https://mainnet.base.org - Radius testnet:
https://rpc.testnet.radiustech.xyz - Polygon:
https://polygon-rpc.com - Arbitrum:
https://arb1.arbitrum.io/rpc
/*- Protect all files (default)/premium/*- Protect only files under /premium//file1.pdf,/folder/*- Protect specific files/folders (comma-separated)
npm run deploy- User requests a protected resource from your R2 bucket
- Worker checks if payment is required for the requested path
- If payment required, returns 402 status with payment details
- User sends USDC payment to specified address
- On subsequent request with valid payment proof, access is granted
- File is served directly from R2 bucket
The worker returns a 402 Payment Required response with an X-Accept-Payment header containing:
- Amount in USDC
- Payment address
- Network RPC endpoint
Clients can use x402-compatible libraries to handle the payment automatically.