Skip to content

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 dotenv

Environment 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
VariableDescription
RESOURCE_SERVER_URLBase URL of the resource server.
ENDPOINT_PATHPath to the paid endpoint.
PRIVATE_KEYYour 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

  1. wrapFetchWithPayment(fetch, account) returns a new function with the same signature as fetch. You can use it as a drop-in replacement.
  2. When the server responds with 402 Payment Required, the wrapper reads the payment requirements from the response headers.
  3. It constructs a signed payment payload using your account and submits it to the facilitator at https://facilitator.svmacc.tech.
  4. The original request is retried with the X-Payment header containing the settled payment proof.
  5. 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 fetch options (method, headers, body, etc.).
  • Payments are only triggered when the server responds with a 402 status code. All other responses pass through unchanged.
  • Keep your private key secure. Never commit .env files to version control.

Powered by SVM Facilitator