Overview
Thex402-express package provides Express.js middleware to protect API routes with the x402 payment protocol. When a request arrives without payment, the middleware responds with 402 Payment Required and payment details. When a valid payment signature is included, the middleware verifies it and allows the request to proceed.
Installation
Basic Usage
API Reference
paymentMiddleware(payTo, routes, options?)
Creates Express middleware that enforces payment requirements on specified routes.
Parameters
payTo(string) - EVM address that receives payments (must be a valid 0x-prefixed address)routes(Record<string, RouteConfig>) - Map of route patterns 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
Route patterns should match the format"METHOD /path", for example:
"GET /ping""POST /tweet""GET /api/data"
Examples
Simple Protected Endpoint
From theping demo (source):
Advanced Configuration with Custom Facilitator
From thesend-tweet demo (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 in the response body - 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
Response Headers
When using x402-express with CORS, make sure to expose theX-PAYMENT-RESPONSE header:
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
Related
- x402-axios - Client-side interceptor for Axios
- x402-hono - Middleware for Hono framework
- x402 Protocol - Understanding the payment protocol