x402

Client Side

Make requests to any x402-compatible backend and automatically handle payment flows when APIs return a 402 Payment Required response.

The client library wraps the native fetch API and handles:

  • Initial request to the API
  • Detection of 402 Payment Required responses
  • Parsing payment requirements from the response
  • Creating and signing payment authorization
  • Retrying the request with payment credentials

Using useFetchWithPayment

The useFetchWithPayment hook is a React-specific wrapper that automatically handles 402 Payment Required responses with built-in UI for payment errors, insufficient funds, and wallet connection.

import { useFetchWithPayment } from "thirdweb/react";
import { createThirdwebClient } from "thirdweb";
const client = createThirdwebClient({ clientId: "your-client-id" });
function MyComponent() {
const { fetchWithPayment, isPending } = useFetchWithPayment(client);
const handleApiCall = async () => {
// Handle wallet connection, funding, and payment errors automatically
// Response is parsed as JSON by default
const data = await fetchWithPayment(
"https://api.example.com/paid-endpoint",
);
console.log(data);
};
return (
<button onClick={handleApiCall} disabled={isPending}>
{isPending ? "Loading..." : "Make Paid API Call"}
</button>
);
}

Features

  • Automatic Payment Handling: Detects 402 responses and creates payment headers automatically
  • Wallet Connection: Prompts users to connect their wallet if not connected
  • Funding: Integrates BuyWidget to help users top up their wallet directly when needed
  • Built-in error handling UI: Shows error modals with retry and fund wallet options
  • Response Parsing: Automatically parses responses as JSON by default

Parameters

  • client - The thirdweb client used to access RPC infrastructure
  • options - (Optional) Configuration object:
    • maxValue - Maximum allowed payment amount in base units
    • parseAs - How to parse the response: "json" (default), "text", or "raw"
    • theme - Theme for the payment error modal: "dark" (default) or "light"
    • uiEnabled - Whether to show the UI for connection, funding or payment retries (defaults to true)
    • fundWalletOptions - Customize the BuyWidget for topping up
    • connectOptions - Customize the ConnectModal for wallet connection

Reference

For full API documentation, see the TypeScript Reference.