Building x402 Payment APIs on Cloudflare Workers with Hono
Step-by-step guide to adding x402 micropayments to Cloudflare Workers using Hono.js middleware. Includes Bazaar registration and cost architecture.
Building x402 Payment APIs on Cloudflare Workers with Hono
There’s a reason Cloudflare Workers and Hono have become the default stack for x402 API services: Workers runs at the edge in 300+ locations with sub-millisecond cold starts, and Hono’s first-class x402 middleware means you’re adding a payment layer to an existing route in under ten lines. The economics work, the latency works, and the deployment model—wrangler deploy—is genuinely frictionless.
This guide walks through the architecture we use at PicoPayd, including how to structure services for testability, how to register in the Bazaar discovery layer, and the cost math that makes micropayment APIs viable.
Why This Stack in Particular
A few things have to be true for a micropayment API to work. First, the service needs to be fast—if your endpoint takes 3 seconds to respond, users will tolerate it with a subscription but resent it at $0.005/call. Workers’ edge deployment keeps latency low globally without you managing infrastructure. Second, your fixed costs need to be low enough that a modest call volume is profitable. Workers’ free tier handles 100,000 requests/day; paid starts at $5/month for 10M requests. That’s a different math than running an EC2 instance.
For x402 specifically, you also want a framework with proper middleware support. Hono’s @x402/hono package integrates cleanly with Hono’s middleware chain—it’s not bolted on, it composes.
Project Structure
Clean architecture matters here, especially once you have multiple services. Here’s the layout we landed on after building five production services:
/packages
/core # Shared modules (config, errors, db, payment middleware)
/services
/image-convert # Individual Cloudflare Worker per service
/html-to-pdf
/qr-code
/image-optimize
/doc-convert
Each service is a separate Worker with its own wrangler.toml and deployment. They share the core package via pnpm workspaces. This isolation matters: a bug in the image conversion service doesn’t affect your QR code service, and you can roll back independently.
The core package contains:
- Configuration: Typed environment config with Zod validation
- Error handling: Consistent error types that map to HTTP status codes
- Payment middleware: Shared x402 setup so every service gets the same payment config
- Analytics: Optional per-call logging to D1
Adding x402 to a Hono Route
The actual payment integration is minimal. Install the package:
pnpm add @x402/hono
Then wrap your routes:
import { Hono } from 'hono'
import { paymentMiddleware } from '@x402/hono'
const app = new Hono<{ Bindings: Env }>()
app.use(
'/convert/*',
paymentMiddleware({
facilitatorUrl: 'https://x402.org/facilitator',
routes: {
'/convert/image': {
price: '$0.005',
network: 'base-mainnet',
config: {
description: 'Convert images between formats (JPEG, PNG, WebP, AVIF)',
mimeType: 'application/json',
}
}
}
})
)
app.post('/convert/image', async (c) => {
// Your handler only runs after payment is verified
// ...
})
That’s the full integration. The middleware handles the 402 challenge/response cycle, signature verification delegation to the facilitator, and only calls next() if payment is verified. Your handler code is clean—no payment logic in business logic.
Structuring for Testability
The temptation is to write everything inline in the Hono handler. Resist it. The right layered structure looks like:
Handler (HTTP in/out)
→ Service (business logic, pure functions)
→ Repository (external I/O: storage, databases)
Your service layer should be pure TypeScript with no Hono imports. This makes unit testing trivial—you call convertImage(input) directly without mocking an HTTP context. Integration tests can use Hono’s app.request() for end-to-end testing including the payment middleware.
// service/image-converter.ts - no framework dependencies
export async function convertImage(
input: Uint8Array,
options: ConversionOptions
): Promise<ConversionResult> {
// Pure business logic here
}
// routes/convert.ts - thin handler
app.post('/convert/image', async (c) => {
const body = await c.req.arrayBuffer()
const options = parseOptions(c.req.query())
const result = await convertImage(new Uint8Array(body), options)
return c.json(result)
})
Unit test coverage on the service layer, integration tests on the routes. Workers’ miniflare handles local testing with full Workers runtime compatibility.
Registering in the x402 Bazaar
The Bazaar is the discovery layer for x402 services. AI agents query it programmatically to find services by capability. Without Bazaar registration, you’re invisible to autonomous discovery—which is exactly the use case x402 is built for.
Registration happens through your payment middleware configuration. The bazaar extension in the CDP facilitator spec expects:
paymentMiddleware({
facilitatorUrl: 'https://x402.org/facilitator',
routes: {
'/convert/image': {
price: '$0.005',
network: 'base-mainnet',
config: {
description: 'Convert images between JPEG, PNG, WebP, and AVIF formats',
mimeType: 'application/json',
inputSchema: {
type: 'object',
properties: {
format: { type: 'string', enum: ['jpeg', 'png', 'webp', 'avif'] },
quality: { type: 'number', minimum: 1, maximum: 100 }
}
},
outputSchema: {
type: 'object',
properties: {
url: { type: 'string' },
format: { type: 'string' },
size: { type: 'number' }
}
}
}
}
}
})
The input/output schemas are what make your service composable. An agent can inspect these schemas and understand whether your service fits into its workflow without making a test call.
Cost Architecture
Here’s the math that makes this viable. At PicoPayd, our fixed costs run about $6/month (Workers paid plan + D1 + R2 for temporary storage). Variable costs are essentially zero—we use free or open-source processing libraries rather than upstream API calls.
At $0.005/call average, you break even at 1,200 calls/month. Anything above that is margin.
This only works because of the “no upstream costs” constraint. Services that resell third-party data (a weather API that costs you $0.003 to fetch and you charge $0.005) have razor-thin margins and no room for error. Services that run algorithms against open data or do stateless transformations (image conversion, document processing, unit conversion, QR generation) keep nearly 100% of revenue.
That’s the core PicoPayd thesis: find services with real utility, implement them algorithmically without expensive data dependencies, and price them at the floor of what makes the x402 model work.
Deployment
# Deploy a single service
cd packages/services/image-convert
wrangler deploy
# Or with Turborepo across all services
turbo run deploy
Each service gets its own subdomain: image-convert.yourdomain.workers.dev. You can also configure custom routes in wrangler.toml to put everything under a single domain.
One gotcha: Workers have a 10ms CPU time limit on the free plan, 50ms on paid. For CPU-intensive operations like PDF generation or image processing, you’ll hit this. The solution is either offloading compute to a Durable Object, using Workers Unbound, or—what we do—being selective about which operations are worth the overhead. Most image conversions run in under 30ms on paid Workers. HTML-to-PDF is heavier and needs careful optimization.
What to Build
The x402 ecosystem has 10,000+ live endpoints but most cluster around DeFi data and AI inference. There’s real demand for utility services that nobody has built yet:
- Validation APIs — IBAN validation, EU VAT number lookup, phone number parsing. These are algorithmic with no upstream costs.
- Unit conversion — 150+ conversion types via mathjs. Single dependency, instant execution, genuinely useful for AI agents building calculations.
- Document utilities — Format conversion, PDF manipulation, metadata extraction.
- Geographic calculations — Distance, timezone lookup, geocoding via OpenStreetMap (free).
The bar isn’t finding novel ideas—it’s finding useful ones and implementing them cleanly on a stack that makes the unit economics work.
Featured Image Suggestion: Split-screen showing clean TypeScript code on the left and a Cloudflare Workers dashboard on the right, with a payment flow diagram between them.