Fetch API Client Example

Use x402 with the native Fetch API

exampletypescriptfetchclientbeginner
Files
2 files in this example

@x402/fetch Example Client

Example client demonstrating how to use @x402/fetch to make HTTP requests to endpoints protected by the x402 payment protocol.

import { x402Client, wrapFetchWithPayment } from "@x402/fetch";
import { registerExactEvmScheme } from "@x402/evm/exact/client";
import { registerExactSvmScheme } from "@x402/svm/exact/client";
import { privateKeyToAccount } from "viem/accounts";
import { createKeyPairSignerFromBytes } from "@solana/kit";
import { base58 } from "@scure/base";

const client = new x402Client();
registerExactEvmScheme(client, { signer: privateKeyToAccount(process.env.EVM_PRIVATE_KEY) });
registerExactSvmScheme(client, { signer: (await createKeyPairSignerFromBytes(base58.decode(process.env.SVM_PRIVATE_KEY))) });

const fetchWithPayment = wrapFetchWithPayment(fetch, client);

const response = await fetchWithPayment("http://localhost:4021/weather");
console.log(await response.json());

Prerequisites

Setup

  1. Install and build all packages from the typescript examples root:
cd ../../
pnpm install && pnpm build
cd clients/fetch
  1. Copy .env-local to .env and add your private keys:
cp .env-local .env

Required environment variables:

  • EVM_PRIVATE_KEY - Ethereum private key for EVM payments
  • SVM_PRIVATE_KEY - Solana private key for SVM payments
  1. Run the client:
pnpm start

Next Steps

See Advanced Examples for builder pattern registration, payment lifecycle hooks, and network preferences.

Related Content

Looking for more? Check out our other typescript examples or browse by client content.