Axios Client
The x402-axios package adds a payment interceptor to Axios instances. When a server responds with 402 Payment Required, the interceptor automatically handles payment settlement through the facilitator and retries the request.
Installation
bash
npm install x402-axios axios viem dotenvEnvironment Setup
Create a .env file in your project root:
RESOURCE_SERVER_URL=https://api.example.com
ENDPOINT_PATH=/api/premium/data
PRIVATE_KEY=0xYOUR_PRIVATE_KEY| Variable | Description |
|---|---|
RESOURCE_SERVER_URL | Base URL of the resource server. |
ENDPOINT_PATH | Path to the paid endpoint. |
PRIVATE_KEY | Your Ethereum-compatible private key. |
Usage
typescript
import axios from "axios";
import { withPaymentInterceptor, decodeXPaymentResponse } from "x402-axios";
import { privateKeyToAccount } from "viem/accounts";
import dotenv from "dotenv";
dotenv.config();
const { RESOURCE_SERVER_URL, ENDPOINT_PATH, PRIVATE_KEY } = process.env;
const account = privateKeyToAccount(PRIVATE_KEY as `0x${string}`);
const client = withPaymentInterceptor(axios.create(), account);
async function main() {
const url = `${RESOURCE_SERVER_URL}${ENDPOINT_PATH}`;
const response = await client.get(url);
console.log("Response:", response.data);
if (response.headers["x-payment-response"]) {
const paymentResponse = decodeXPaymentResponse(
response.headers["x-payment-response"]
);
console.log("Payment:", paymentResponse);
}
}
main().catch(console.error);How It Works
withPaymentInterceptor(axiosInstance, account)attaches request and response interceptors to the provided Axios instance.- When the server responds with
402 Payment Required, the response interceptor reads the payment requirements from the response headers. - It constructs a signed payment payload using your account and submits it to the facilitator at
https://facilitator.svmacc.tech. - The original request is retried with the
X-Paymentheader containing the settled payment proof. - The server validates the payment and returns the resource.
Reading the Payment Response
After a successful paid request, the server includes an x-payment-response header. Use decodeXPaymentResponse to parse it:
typescript
if (response.headers["x-payment-response"]) {
const paymentResponse = decodeXPaymentResponse(
response.headers["x-payment-response"]
);
console.log("Transaction hash:", paymentResponse.txHash);
}This header contains details about the settled payment, including the on-chain transaction hash.
Notes
- The interceptor works with any Axios instance created via
axios.create(). You can configure base URLs, default headers, and other Axios options as usual. - Payments are only triggered when the server responds with a
402status code. All other responses pass through unchanged. - Axios automatically normalizes header names to lowercase, so the payment response header is accessed as
response.headers["x-payment-response"]. - Keep your private key secure. Never commit
.envfiles to version control.