Express Integration
The @shade402/express package provides middleware and utilities for implementing X402 payment-protected endpoints in Express.js applications.
Installation
pnpm add @shade402/express @shade402/coreBasic Setup
Initialize Configuration
Initialize X402 with your payment configuration:
import { initX402 } from '@shade402/express';
initX402({
paymentAddress: process.env.PAYMENT_WALLET_ADDRESS!,
tokenMint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', // USDC
network: 'solana-devnet',
rpcUrl: process.env.SOLANA_RPC_URL,
defaultAmount: '0.01',
paymentTimeout: 300, // 5 minutes
autoVerify: true,
});Protect Routes
Use the paymentRequired middleware to protect routes:
Configuration Options
Global Configuration
Per-Route Configuration
You can override global configuration for specific routes:
Accessing Payment Information
Payment information is available on the request object after verification:
Error Handling
Add the error middleware at the end of your middleware stack:
The error middleware handles:
PaymentRequiredError: Returns 402 with payment requestPaymentExpiredError: Returns 410 GoneInsufficientFundsError: Returns 402PaymentVerificationError: Returns 403 ForbiddenTransactionBroadcastError: Returns 502 Bad GatewayInvalidPaymentRequestError: Returns 400 Bad Request
Resource Encryption
Enable resource encryption for enhanced privacy:
With encryption enabled, the server will:
Include public key in 402 response headers
Automatically decrypt encrypted resource from client requests
Make decrypted resource available via
req.decryptedResource
Multiple Payment Tiers
Implement different payment tiers:
Manual Payment Verification
For custom verification logic, disable automatic verification:
Building 402 Responses Manually
For custom payment flow control:
Complete Example
Best Practices
Initialize X402 configuration once at application startup
Store sensitive configuration in environment variables
Use appropriate payment amounts for different tiers
Set reasonable expiration times for payment requests
Enable automatic verification in production
Add error middleware after all routes
Use TypeScript types for better type safety
Monitor payment verification failures
Consider rate limiting for payment-protected endpoints
Log payment transactions for audit purposes
Next Steps
Learn about Client Usage for making requests
Check out Security best practices
See Examples for more use cases
Last updated
