Fetch Client
The x402-fetch package wraps the native fetch API with automatic x402 payment handling. When a server responds with 402 Payment Required, the wrapper constructs a payment payload, settles it through the facilitator, and retries the request transparently.
Installation
bash
npm install x402-fetch 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 { wrapFetchWithPayment } from "x402-fetch";
import { privateKeyToAccount } from "viem/accounts";
import { decodeXPaymentResponse } from "x402-fetch";
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 fetchWithPayment = wrapFetchWithPayment(fetch, account);
async function main() {
const url = `${RESOURCE_SERVER_URL}${ENDPOINT_PATH}`;
const response = await fetchWithPayment(url);
const body = await response.json();
console.log("Response:", body);
if (response.headers.has("x-payment-response")) {
const paymentResponse = decodeXPaymentResponse(
response.headers.get("x-payment-response")!
);
console.log("Payment:", paymentResponse);
}
}
main().catch(console.error);How It Works
wrapFetchWithPayment(fetch, account)returns a new function with the same signature asfetch. You can use it as a drop-in replacement.- When the server responds with
402 Payment Required, the wrapper 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.has("x-payment-response")) {
const paymentResponse = decodeXPaymentResponse(
response.headers.get("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 wrapped fetch function supports all standard
fetchoptions (method,headers,body, etc.). - Payments are only triggered when the server responds with a
402status code. All other responses pass through unchanged. - Keep your private key secure. Never commit
.envfiles to version control.