Build an L402 API Paywall with Cloudflare Workers
Step-by-step guide to building a pay-per-request API using HTTP 402 and Lightning invoices
Build an L402 API Paywall with Cloudflare Workers
HTTP has a status code for payments: 402 Payment Required. It sat unused for decades. L402 gives it a purpose.
When a client hits your API without paying, you return a 402 with a Lightning invoice. The client pays, retries with proof, and gets the response. No API keys. No subscriptions. No billing dashboards.
The Stack
- Cloudflare Workers — serverless runtime, free tier
- LNbits — Lightning wallet with REST API (runs on Alby Hub, your own node, or lnbits.com)
The Flow
- Client POSTs to your API
- Worker creates a Lightning invoice via LNbits
- Returns HTTP 402 with the invoice
- Client pays the invoice
- Client retries with the payment_hash
- Worker verifies payment via LNbits
- Returns the data
Full tutorial with working code: https://maximumsats.com/blog/l402-api-paywall-cloudflare-workers
Covers setup, deployment, the WWW-Authenticate header for automated clients, free tier implementation, and CORS.
The entire deployment costs $0. Revenue is 100% margin. This is how APIs should work in a world with programmable money.
No comments yet.