Overview
Thex402-axios package provides an Axios interceptor that automatically handles the x402 payment protocol. When a server responds with 402 Payment Required, the interceptor signs the payment and retries the request automatically.
Installation
Basic Usage
API Reference
withPaymentInterceptor(axiosInstance, signer)
Adds x402 payment handling to an Axios instance via request and response interceptors.
Parameters
axiosInstance(AxiosInstance) - The Axios instance to add interceptors tosigner(Signer) - An x402-compatible signer for creating payment signatures
Returns
void - Modifies the axios instance in-place by adding interceptors
Signer Interface
The signer must implement:Examples
Next.js Client Application
From thesend-tweet demo (source):
Creating x402-Compatible Signer
From the Crossmint wallet adapter (source):Custom Request/Response Logging
Add additional interceptors for debugging:How It Works
- Initial Request: You make a request with axios
- Intercept 402: If server responds with
402 Payment Required, the interceptor catches it - Parse Requirements: Extract payment details from the 402 response body
- Sign Payment: Use the provided signer to create an EIP-712 signature
- Retry with Payment: Automatically retry the same request with
X-PAYMENTheader - Return Response: Return the successful response to your code
Payment Headers
The interceptor automatically manages these headers:- Request:
Accept: application/vnd.x402+json(you must add this manually) - Retry:
X-PAYMENT: <signature>(added automatically by interceptor) - Response:
X-PAYMENT-RESPONSE: <receipt>(payment confirmation from server)
Error Handling
The interceptor preserves standard Axios error behavior:- 402 persists: Signature verification failed or insufficient balance
- Network errors: Standard axios network issues
- Signature errors: Wallet not properly initialized
CORS Configuration
When using with a CORS-enabled API, ensure the server exposes payment headers:TypeScript Types
Best Practices
- Always add Accept header: Include
Accept: application/vnd.x402+jsonin requests to payment-protected endpoints - Check wallet deployment: For smart wallets, verify deployment before making payments
- Handle errors gracefully: Check for 402 status in error handlers
- Add custom logging: Use additional interceptors for debugging payment flows
- Test with testnet: Use Base Sepolia testnet tokens for development
Related
- x402-fetch - Fetch API wrapper for x402
- x402-express - Server-side middleware for Express
- Crossmint Wallets - Creating payment-enabled wallets