Create Your First Fetch Client

Use x402 with the standard Fetch API to make paid HTTP requests. Perfect for both browser and Node.js environments.
1

Install Dependencies

Create a new project and install the required packages:
mkdir my-fetch-client && cd my-fetch-client
pnpm init -y
pnpm add x402-fetch @coinbase/x402 viem dotenv tsx
Expected outcome: Project directory created with x402 fetch client dependencies installed.
2

Environment Configuration

Create a .env file in your project root:
# Required: Your private key for making payments
PRIVATE_KEY=0xYourPrivateKeyHere

# Required: The server URL hosting the paid API
RESOURCE_SERVER_URL=http://localhost:4021

# Required: The endpoint path to access
ENDPOINT_PATH=/weather
Security Note: Never commit private keys to version control. Use environment variables or secure key management services in production. For testing, you can use a dummy private key.
Expected outcome: Environment variables configured for your fetch client.
3

Create the fetch client

Create fetch-client.ts with the payment-enabled fetch implementation:
import { config } from "dotenv";
import { Hex } from "viem";
import { privateKeyToAccount } from "viem/accounts";
import {
  wrapFetchWithPayment,
  decodeXPaymentResponse,
} from "x402-fetch";

config();

const privateKey = process.env.PRIVATE_KEY as Hex;
const baseURL = process.env.RESOURCE_SERVER_URL as string;
const endpointPath = process.env.ENDPOINT_PATH as string;
const url = `${baseURL}${endpointPath}`;

if (!baseURL || !privateKey || !endpointPath) {
  console.error("Missing required environment variables");
  process.exit(1);
}

// Create account from private key
const account = privateKeyToAccount(privateKey);

// Wrap fetch with payment handling
const fetchWithPayment = wrapFetchWithPayment(fetch, account);

// Make a paid request
fetchWithPayment(url, {
  method: "GET",
})
  .then(async (response) => {
    const body = await response.json();
    console.log("Response:", body);

    // Decode the payment response
    const paymentResponse = decodeXPaymentResponse(
      response.headers.get("x-payment-response")!
    );
    console.log("Payment details:", paymentResponse);
  })
  .catch((error) => {
    console.error("Error:", error.message);
  });
Expected outcome: Fetch client code created with automatic payment handling.
4

Run your fetch client

Execute your fetch client to make paid requests:
pnpx tsx fetch-client.ts
Expected outcome: The client should automatically handle the 402 Payment Required response, make the payment, and receive the protected content.
Make sure your paid API server is running on the configured URL. The fetch client will automatically detect 402 responses, handle payment processing, and retry the request with payment proof.
Example successful output:
Response: {
  report: {
    weather: 'sunny',
    temperature: 70
  }
}
Payment details: {
  success: true,
  transaction: '0x1234567890abcdef...',
  network: 'sei-testnet',
  payer: '0xYourWalletAddress...'
}