x402 Payment Middleware
Relevant source files
The following files were used as context for generating this wiki page:
The x402 Payment Middleware is a specialized security and monetization layer implemented within the Recoup API to facilitate crypto-based payments on the Base network. Built on the x402-next framework and integrated with Coinbase's x402 facilitator, it allows the application to enforce paywalls on specific API routes, requiring users to submit valid blockchain payments before accessing premium resources.
This system operates as a Next.js middleware, intercepting incoming requests to validated paths. It serves as a bridge between standard RESTful interactions and decentralized finance, ensuring that high-compute tasks—such as AI image generation—are adequately compensated via automated, on-chain transactions.
Sources: middleware.ts:1-74, README.md:1-40, CLAUDE.md:23-28
Architecture and Integration
The middleware is integrated into the Next.js App Router architecture, specifically targeting routes defined in the middleware configuration matcher. It relies on the x402-next package for the core logic and @coinbase/x402 for the payment facilitator.
Core Components
| Component | Description |
|---|---|
paymentMiddleware | The primary higher-order function from x402-next that wraps the middleware logic. |
facilitator | The Coinbase x402 facilitator used to verify and process payments. |
SMART_ACCOUNT_ADDRESS | The destination Ethereum/Base address where payments are received. |
inputSchema | Defines the expected parameters for the protected route (e.g., query params). |
outputSchema | Defines the JSON structure of the successful response for discoverability. |
Sources: middleware.ts:1-60, package.json:52-54
Data Flow Diagram
The following diagram illustrates the lifecycle of a request through the x402 middleware.
Sources: README.md:42-80, middleware.ts:62-74
Middleware Configuration
The middleware is configured with a mapping of routes to their specific pricing and network requirements. In the Recoup API, this is primarily used for AI services.
Route Definitions
The application currently protects the image generation endpoint with the following configuration:
- Endpoint:
GET /api/x402/image/generate - Price: Dynamic, based on
IMAGE_GENERATE_PRICEconstant. - Network: Base (Layer 2).
- Discoverable: Enabled (allows clients to programmatically find payment requirements).
Sources: middleware.ts:65-73, dev/API-AGENT.md:26-30
Technical Implementation
The middleware is exported with a matcher that defines the scope of protection. While currently focused on specific API routes, the matcher is broad enough to cover potential future protected paths.
export const config = {
matcher: ["/protected/:path*", "/api/:path*"],
runtime: "nodejs",
};
Sources: middleware.ts:84-88
Payment Interaction Model
The system follows the HTTP 402 "Payment Required" status code pattern. When a resource is requested without a valid payment, the middleware returns a structured error response containing the paymentRequirements object.
Payment Requirements Schema
The middleware provides the client with all necessary metadata to complete the transaction:
| Field | Description |
|---|---|
scheme | Usually "exact" for fixed-price resources. |
network | The blockchain network (e.g., "base"). |
maxAmountRequired | The cost in the smallest unit of the asset. |
payTo | The recipient wallet address. |
asset | The contract address of the payment token. |
description | Human-readable description of the purchase. |
Sources: README.md:52-69, middleware.ts:69-70
Image Generation Schema
A significant part of the x402 configuration in middleware.ts involves defining the imageGenerateOutputSchema. This schema ensures that clients paying for the service know exactly what data structure to expect upon successful verification. It includes fields for the base64 image data, usage token statistics, and arweaveResult for decentralized storage tracking.
Sources: middleware.ts:13-54
Conclusion
The x402 Payment Middleware provides a robust, decentralized monetization layer for the Recoup API. By leveraging the Base network and the x402 protocol, it automates the verification of crypto payments at the edge, ensuring that resource-intensive API operations are secured and compensated without requiring traditional centralized payment processors.