Next.js App Example with X402 Payment Support¶
This example demonstrates how to create a Next.js application with X402 payment requirements for API endpoints, including both server-side API routes and client-side payment handling.
Features¶
- Next.js App Router - Modern Next.js 14 with App Router
- Server-side API Routes - Protected endpoints with payment requirements
- Client-side Payment Handling - React components with automatic payment flow
- Free and Premium Endpoints - Mix of public and paid content
- TypeScript - Full type safety
- Tailwind CSS - Modern styling
- X402 Protocol - Blockchain-based micropayments
Setup¶
1. Install Dependencies¶
From the monorepo root:
Or from npm:
2. Configure Environment¶
Create a .env.local file based on .env.example:
Edit .env.local with your Solana wallet details:
3. Build and Run¶
The app will start on http://localhost:3000.
API Endpoints¶
Free Endpoints¶
- GET /api - API information (no payment)
- GET /api/free-data - Free data access (no payment)
Paid Endpoints¶
- GET /api/premium-data - Premium data (0.10 USDC)
- GET /api/expensive-data - AI inference (1.00 USDC)
- GET /api/tiered-data/[tier] - Tiered content (0.05 USDC)
- POST /api/process-data - Data processing (0.25 USDC)
How It Works¶
Server-Side (API Routes)¶
- Initialize X402 Configuration (
app/api/config.ts):
- Protect API Routes with
withPayment:
Client-Side (React Components)¶
- Setup X402 Client Provider (
app/components/X402ClientProvider.tsx):
- Make Requests (automatic payment handling):
Payment Flow¶
- User clicks "Try Endpoint" button
- Client makes request to API endpoint
- Server responds with 402 Payment Required (if no payment)
- Client detects 402 and creates payment
- Client retries request with payment authorization
- Server verifies payment on-chain
- Server returns protected content
Browser Wallet Integration¶
To integrate with browser wallets in production:
Development Tips¶
- Testing without funds: The demo will show payment required errors, which is expected behavior
- Hot reload: Changes to API routes and components are automatically reflected
- TypeScript: Full type checking for both client and server code
- Tailwind CSS: Utility-first styling for rapid UI development