A Next.js application demonstrating a payment-gated API using the x402 protocol.
General flow:
- User connects their wallet
- User requests backend API
- API responds with 402 response code
- User is prompted to sign an authorization
- Server uses thirdweb x402 facilitator to verify and settle payment on abstract testnet
- API returns premium content if payment is successful (HTTP 200)
- Clone the repository:
git clone https://github.com/jarrodwatts/x402-gated-api.git
cd x402-gated-api- Install dependencies:
pnpm install- Configure environment variables:
Copy env.example to .env.local:
cp env.example .env.localEdit .env.local and add your credentials:
NEXT_PUBLIC_THIRDWEB_CLIENT_ID=your_client_id_here
THIRDWEB_SECRET_KEY=your_secret_key_here
SERVER_WALLET_ADDRESS=your_server_wallet_address_hereYou can get these values from your Thirdweb dashboard.
Important: Ensure you fund the server wallet address with some ETH on the network of your choice.
- Run the development server:
pnpm dev- Open http://localhost:3000 in your browser.
Client Side (app/page.tsx)
- Users connect their wallet using Thirdweb's
ConnectButton - The
wrapFetchWithPaymentfunction wraps standard fetch to automatically handle payment requests - When accessing premium content, the client sends payment data with the request
Server Side (app/api/route.ts)
- The API route receives requests with payment data in the
x-paymentheader settlePaymentvalidates and processes the payment on Abstract Testnet- Returns premium content if payment is successful (HTTP 200)
- Returns payment request details if payment is required (HTTP 402)
x402/
├── app/
│ ├── api/
│ │ └── route.ts # Payment-gated API endpoint
│ ├── layout.tsx # Root layout
│ ├── page.tsx # Main page with wallet connection
│ └── globals.css # Global styles
├── components/
│ └── ui/ # shadcn/ui components
├── lib/
│ └── utils.ts # Utility functions
└── env.example # Environment variables template