React Hook for x402 Payments

Joaquim Verges

We just shipped the new useFetchWithPayment() React hook in thirdweb v5.113.0, making it easier than ever to integrate x402 payment flows into your React applications with built-in UI for wallet connection, funding, and payment error handling.

0:00
/0:38

Features

The useFetchWithPayment() hook provides a complete payment experience out of the box:

  • Automatic Payment Handling - Detects 402 responses and creates payment authorization headers automatically
  • Wallet Connection Flow - Prompts users to connect their wallet with a beautiful modal when needed
  • Wallet Funding Integration - Shows a BuyWidget to help users top up their wallet when they have insufficient funds
  • Error Handling UI - Displays modals with retry options when payments fail
  • Response Parsing - Automatically parses responses as JSON by default (configurable)
  • Fully Customizable - Customize themes, wallet options, funding widget, and more
  • React Query Integration - Built on `@tanstack/react-query` for state management

Usage

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>
);
}

Customization Options

const { fetchWithPayment } = useFetchWithPayment(client, {
// Maximum payment amount (in base units)
maxValue: 5000000n, // 5 USDC
// Response parsing: "json" (default), "text", or "raw"
parseAs: "json",
// UI theme: "dark" (default) or "light"
theme: "light",
// Disable UI to handle errors manually
uiEnabled: true,
// Customize the funding widget
fundWalletOptions: {
title: "Add Funds",
description: "Top up your wallet to continue",
},
// Customize the wallet connection modal
connectOptions: {
wallets: [inAppWallet(), createWallet("io.metamask")],
title: "Sign in to continue",
},
});

Platform Support

The hook is available for both web and React Native:

  • Web: Full UI support with modals for connection, funding, and errors
  • React Native: Core functionality without modal UI (coming soon)

Resources

Getting Started

Install the thirdweb SDK if you haven't already:

npm install thirdweb

Then import and use the hook in your React components as shown above.

Happy Building! 🛠️