Overview
Thex402-hono package provides Hono middleware to protect API routes with the x402 payment protocol. It’s designed for Cloudflare Workers, Durable Objects, and edge runtime environments.
Installation
Basic Usage
API Reference
paymentMiddleware(payTo, routes, options?)
Creates Hono middleware that enforces payment requirements on specified routes.
Parameters
payTo(0x${string}) - EVM address that receives payments (must be a valid 0x-prefixed address)routes(Record<string, RouteConfig>) - Map of route paths to payment configurationsoptions(object, optional) - Additional configuration optionsurl(string) - Facilitator URL for payment settlement (default:"https://x402.org/facilitator")createAuthHeaders(function, optional) - Custom function to create authorization headers for facilitator
Route Configuration
Each route in theroutes object has the following properties:
Route Pattern Matching
Unlike Express, Hono routes use path-only patterns (no HTTP method prefix):"/protected-route""/api/data""/mcp/tools"
Examples
Cloudflare Worker with MCP Server
From thecloudflare-agents demo (source):
MCP Tools with x402 Payments
From theevents-concierge agent integration (source):
Multiple Protected Routes
How It Works
- Initial Request: Client makes a request to a protected route
- 402 Response: Middleware responds with
402 Payment Requiredand includes payment details - Client Signs: Client creates an EIP-712 typed data signature authorizing the payment
- Retry with Payment: Client retries the request with an
X-PAYMENTheader containing the signature - Verification: Middleware verifies the signature and forwards to the facilitator for settlement
- Success: If payment is valid, the request proceeds to the route handler
Cloudflare Workers Configuration
When deploying to Cloudflare Workers, configure CORS headers:Error Handling
The middleware handles payment errors automatically:- Returns
402 Payment Requiredwhen payment is missing - Returns
402 Payment Requiredwhen signature verification fails - Returns
500 Internal Server Errorfor facilitator communication errors
Durable Objects Integration
When using with Cloudflare Durable Objects:Related
- x402-fetch - Client-side wrapper for fetch API
- x402-express - Middleware for Express.js
- Events Concierge - Production example with MCP integration