Next.js Integration
The @shade402/nextjs package provides middleware and utilities for implementing X402 payment-protected routes in Next.js applications.
Installation
pnpm add @shade402/nextjs @shade402/coreSetup
Initialize Configuration
Initialize X402 in your Next.js application. Create a configuration file:
// lib/x402-config.ts
import { initX402 } from '@shade402/nextjs';
export function configureX402() {
if (typeof window === 'undefined') {
// Server-side only
initX402({
paymentAddress: process.env.PAYMENT_WALLET_ADDRESS!,
tokenMint: process.env.TOKEN_MINT!,
network: process.env.SOLANA_NETWORK || 'solana-devnet',
rpcUrl: process.env.SOLANA_RPC_URL,
autoVerify: true,
defaultAmount: '0.01',
paymentTimeout: 300,
});
}
}Call this in your API routes or middleware:
API Routes
Protect API routes using the withPayment wrapper:
Pages Router
For Pages Router (app/pages directory):
Configuration Options
Accessing Payment Information
Payment information is available in the handler context:
Error Handling
The withPayment wrapper automatically handles errors and returns appropriate HTTP status codes:
402: Payment required
403: Payment verification failed
410: Payment expired
500: Internal server error
For custom error handling, you can catch errors in your handler:
Multiple Payment Tiers
Implement different payment tiers:
Environment Variables
Set up environment variables in .env.local:
Complete Example
Client-side Integration
For client-side requests, use the @shade402/client package:
Best Practices
Initialize X402 configuration in a shared utility file
Store sensitive configuration in environment variables
Use appropriate payment amounts for different routes
Enable automatic verification in production
Use TypeScript types for better type safety
Handle errors gracefully in your handlers
Consider rate limiting for payment-protected routes
Log payment transactions for audit purposes
Next Steps
Learn about Client Usage for making requests
Check out Express Integration for comparison
See Examples for more use cases
Last updated
