Package Exports
- x402-analytics
- x402-analytics/buyer
- x402-analytics/seller
Readme
x402-analytics
Analytics wrapper for x402 payment protocol - Track payment events, performance metrics, and transaction data for both buyers and sellers with zero configuration.
๐ Quick Start
For Buyers (Client-side)
import { withBuyerAnalytics } from 'x402-analytics';
// Wrap your x402 fetch function with analytics
const fetchWithAnalytics = await withBuyerAnalytics(fetchWithPayment);
// Use it like normal - analytics happen automatically!
const response = await fetchWithAnalytics('https://api.example.com/data', {
payment: { maxAmountRequired: '10000' }
});For Sellers (Server-side)
import { withSellerAnalytics } from 'x402-analytics';
import express from 'express';
const app = express();
// Wrap your x402 middleware with analytics
const analytics = await withSellerAnalytics(x402Middleware);
app.use('/api', analytics);
// All requests are now tracked automatically!โจ Features
- ๐ฏ Zero Configuration: Works immediately without API keys or setup
- ๐ Real-time Dashboard: Get instant analytics at
https://x402station.com/dashboard/anonymous/{your-id} - ๐ Claim Token System: Secure anonymous project claiming with claim tokens
- ๐ Automatic Tracking: Captures all payment events, errors, and performance metrics
- โก Non-blocking: Analytics don't slow down your application
- ๐ก๏ธ Resilient: Built-in retry logic, circuit breakers, and offline persistence
- ๐ Universal: Works in browsers, Node.js, and serverless environments
- ๐ฑ TypeScript: Full TypeScript support with comprehensive type definitions
๐ฆ Installation
npm install x402-analyticsPeer Dependencies: This package requires x402 v0.6.6 or higher.
๐ฏ Zero-Config Mode
The easiest way to get started - no API key required:
import { withBuyerAnalytics } from 'x402-analytics';
// Zero-config: Analytics work immediately
const fetchWithAnalytics = await withBuyerAnalytics(fetchWithPayment);
// You'll see this in your console:
// ๐ x402 Analytics Dashboard: https://x402station.com/dashboard/anonymous/abc123
// ๐ก Save your claim token to upgrade later (stored locally)
// ๐ Claim Token: your-secure-claim-token๐ API Key Mode
For production use and data retention beyond 24 hours:
import { withBuyerAnalytics } from 'x402-analytics';
const fetchWithAnalytics = await withBuyerAnalytics(fetchWithPayment, {
apiKey: process.env.X402_ANALYTICS_API_KEY
});๐ What Gets Tracked
Buyer Events
- Request Details: URL, payment amount, success/failure
- Performance: Response time, duration
- Payment Data: Transaction hash, payer address, network
- Error Information: Error messages and failure reasons
Seller Events
- Request Details: Path, payment amount, success/failure
- Performance: Response time, duration
- Payment Data: Transaction hash, payer address, network
- Error Information: HTTP status codes and error messages
๐ ๏ธ Configuration Options
Buyer Configuration
interface BuyerConfig {
apiKey?: string; // API key for data retention
anonymousId?: string; // Custom anonymous ID
userId?: string; // User identifier
batchSize?: number; // Events per batch (default: 100)
flushInterval?: number; // Flush interval in ms (default: 10000)
enableRetry?: boolean; // Enable retry logic (default: true)
maxRetries?: number; // Max retry attempts (default: 3)
claimToken?: string; // Custom claim token for anonymous projects
}Seller Configuration
interface SellerConfig {
apiKey?: string; // API key for data retention
anonymousId?: string; // Custom anonymous ID
userId?: string; // User identifier
batchSize?: number; // Events per batch (default: 100)
flushInterval?: number; // Flush interval in ms (default: 10000)
enableRetry?: boolean; // Enable retry logic (default: true)
maxRetries?: number; // Max retry attempts (default: 3)
claimToken?: string; // Custom claim token for anonymous projects
}๐ง Advanced Usage
Custom Configuration
const fetchWithAnalytics = await withBuyerAnalytics(fetchWithPayment, {
apiKey: process.env.X402_ANALYTICS_API_KEY,
batchSize: 50,
flushInterval: 5000,
enableRetry: true,
maxRetries: 5
});Express Middleware Integration
import express from 'express';
import { withSellerAnalytics } from 'x402-analytics';
const app = express();
// Apply analytics to specific routes
app.use('/api', await withSellerAnalytics(x402Middleware, {
apiKey: process.env.X402_ANALYTICS_API_KEY
}));
// Or apply globally
app.use(await withSellerAnalytics(x402Middleware));Multiple Analytics Instances
// Different configurations for different services
const userAnalytics = await withBuyerAnalytics(userFetch, {
userId: 'user-123',
batchSize: 25
});
const adminAnalytics = await withBuyerAnalytics(adminFetch, {
userId: 'admin-456',
batchSize: 100
});๐ Claim Token System
The SDK includes a secure claim token system for anonymous projects:
How It Works
- Anonymous Mode: When no API key is provided, the SDK generates a unique anonymous ID and claim token
- Secure Storage: Claim tokens are stored locally and securely hashed before transmission
- Project Claiming: Use your claim token to upgrade anonymous projects to full accounts
- Data Retention: Claimed projects retain data beyond the 24-hour anonymous limit
Using Claim Tokens
// The SDK automatically generates and displays your claim token
const analytics = await withSellerAnalytics(x402Middleware);
// Console output:
// ๐ x402 Analytics Dashboard: https://x402station.com/dashboard/anonymous/abc123
// ๐ก Save your claim token to upgrade later (stored locally)
// ๐ Claim Token: your-secure-claim-token-here
// Use the claim token to upgrade your project at x402station.comCustom Claim Tokens
// Provide your own claim token
const analytics = await withSellerAnalytics(x402Middleware, {
claimToken: 'your-custom-claim-token'
});๐ Environment Variables
| Variable | Description | Default |
|---|---|---|
X402_ANALYTICS_API_KEY |
API key for data retention | None (uses anonymous mode) |
X402_ANALYTICS_SILENT |
Disable console logging | false |
X402_ANALYTICS_DEV_MODE |
Log events instead of sending | false |
๐ Development Mode
For development and testing:
# Log events to console instead of sending to analytics service
X402_ANALYTICS_DEV_MODE=true npm run dev๐ Analytics Dashboard
Visit your dashboard at https://x402station.com/dashboard/anonymous/{your-id} to see:
- Real-time Metrics: Live request tracking and performance data
- Payment Analytics: Transaction volumes, success rates, and revenue
- Error Monitoring: Failed requests and error patterns
- Performance Insights: Response times and optimization opportunities
- Claim Token Management: Secure anonymous project claiming
๐ก๏ธ Reliability Features
Automatic Retry Logic
- Exponential backoff for failed requests
- Configurable retry attempts
- Circuit breaker pattern to prevent cascading failures
Offline Persistence
- Failed events stored in localStorage (browser) or memory (Node.js)
- Automatic retry on next session
- Graceful degradation when analytics service is unavailable
Error Handling
- Non-blocking analytics - failures don't affect your application
- Comprehensive error logging and monitoring
- Graceful fallbacks for all failure scenarios
๐งช Testing
import { withBuyerAnalytics } from 'x402-analytics';
// Mock fetch for testing
const mockFetch = jest.fn().mockResolvedValue({
json: () => Promise.resolve({ data: 'test' }),
headers: { get: () => null }
});
const analyticsFetch = await withBuyerAnalytics(mockFetch);
// Test your analytics integration
const result = await analyticsFetch('https://api.test.com/data');
expect(result).toBeDefined();๐ Examples
Check out the complete examples in the repository:
- Buyer Example: Client-side integration
- Seller Example: Server-side Express integration
๐ Links
- Documentation: coming soon !
- Dashboard: coming soon !
- x402 Protocol: https://www.x402.org/
๐ Support
- GitHub Issues: Report bugs or request features
- Discord: Join our community
- Email: admin@remslabs.com
Made with โค๏ธ by RemsLabs