x402-fetch Example Client
This is an example client that demonstrates how to use the x402-fetch package to make HTTP requests to endpoints protected by the x402 payment protocol.
Prerequisites
- Node.js v20+ (install via nvm)
- pnpm v10 (install via pnpm.io/installation)
- A running x402 server (you can use the example express server at
examples/typescript/servers/express) - A valid Ethereum private key for making payments
Setup
- Install and build all packages from the typescript examples root:
cd ../../
pnpm install
pnpm build
cd clients/fetch
- Copy
.env-localto.envand add your Ethereum private key:
cp .env-local .env
- Start the example client:
pnpm dev
How It Works
The example demonstrates how to:
- Create a wallet client using viem
- Wrap the native fetch function with x402 payment handling
- Make a request to a paid endpoint
- Handle the response or any errors
Example Code
import { config } from "dotenv";
import { createWalletClient, http } from "viem";
import { privateKeyToAccount } from "viem/accounts";
import { wrapFetchWithPayment } from "x402-fetch";
import { baseSepolia } from "viem/chains";
config();
const { RESOURCE_SERVER_URL, PRIVATE_KEY, ENDPOINT_PATH } = process.env;
// Create wallet client
const account = privateKeyToAccount(PRIVATE_KEY as `0x${string}`);
const client = createWalletClient({
account,
transport: http(),
chain: baseSepolia,
});
// Wrap fetch with payment handling
const fetchWithPay = wrapFetchWithPayment(fetch, client);
// Make request to paid endpoint
fetchWithPay(`${RESOURCE_SERVER_URL}${ENDPOINT_PATH}`, {
method: "GET",
})
.then(async response => {
const body = await response.json();
console.log(body);
})
.catch(error => {
console.error(error.response?.data?.error);
});