@analytix402/sdk
v0.1.3
Published
Monitor, secure, and optimize your x402 APIs. Real-time analytics, security scanning, and revenue tracking.
Maintainers
Readme
@analytix402/sdk
Monitor, secure, and optimize your x402 APIs. Drop-in Express middleware that captures requests, payments, and performance data — viewable on analytix402.com.
Installation
npm install @analytix402/sdkQuick Start
import express from 'express';
import { Analytix402 } from '@analytix402/sdk';
const app = express();
// Add Analytix402 middleware (before your routes)
app.use(Analytix402({
apiKey: 'ax_live_your_key_here',
}));
// Your x402 routes
app.get('/api/data', (req, res) => {
res.json({ data: 'Hello World' });
});
app.listen(3000);That's it! Revenue, requests, and security data will appear in your Analytix402 dashboard.
What Gets Tracked
The SDK automatically captures:
- Request data: Method, path, status code, response time
- Payment data: Amount, currency, payer wallet (from x402 headers)
- Metadata: IP address, user agent, timestamp
All data is batched and sent asynchronously — your API response times are not affected.
Configuration
app.use(Analytix402({
// Required: Your API key from the Analytix402 dashboard
apiKey: 'ax_live_xxxxx',
// Optional: Custom API endpoint (for self-hosted)
baseUrl: 'https://api.analytix402.com',
// Optional: Enable debug logging
debug: false,
// Optional: Batch size before sending (default: 100)
batchSize: 100,
// Optional: Flush interval in ms (default: 5000)
flushInterval: 5000,
// Optional: Max retries for failed requests (default: 3)
maxRetries: 3,
// Optional: Max events to queue offline (default: 1000)
maxQueueSize: 1000,
// Optional: Request timeout in ms (default: 10000)
timeout: 10000,
// Optional: Paths to exclude from tracking
excludePaths: ['/health', '/internal/*'],
// Optional: Custom endpoint naming
getEndpointName: (req) => {
// Group by route pattern instead of full path
return req.path.replace(/\/[0-9a-f-]+/g, '/:id');
},
// Optional: Custom filtering
shouldTrack: (req) => {
// Only track API routes
return req.path.startsWith('/api/');
},
}));x402 Payment Headers
The SDK automatically reads these headers set by x402 facilitators:
| Header | Description |
|--------|-------------|
| x-payment | Payment receipt/proof |
| x-payment-token | Payment JWT |
| x-payer | Payer wallet address |
| x-payment-amount | Payment amount |
| x-payment-currency | Currency (e.g., USDC) |
| x-payment-tx | Transaction hash |
| x-facilitator | Facilitator URL |
Default Excluded Paths
These paths are excluded from tracking by default:
/health, /healthz, /ready, /readyz, /live, /livez, /metrics, /favicon.ico, /.well-known
Agent Tracking
Track AI agent health, tasks, and LLM usage:
import { createAnalytix402Client } from '@analytix402/sdk';
const client = createAnalytix402Client({
apiKey: 'ax_live_xxxxx',
agentId: 'my-trading-agent',
agentName: 'Trading Bot',
});
// Send heartbeats to show agent is alive
setInterval(() => {
client.heartbeat('healthy', { uptime: process.uptime() });
}, 30000);
// Track tasks with automatic duration measurement
const task = client.startTask('rebalance-portfolio-42');
try {
await doRebalance();
task.end(true, { positions: 12 });
} catch (err) {
task.end(false, { error: err.message });
}
// Track LLM token usage
client.trackLLM({
model: 'claude-sonnet-4-5-20250929',
provider: 'anthropic',
inputTokens: 1500,
outputTokens: 300,
costUsd: 0.012,
durationMs: 820,
taskId: 'rebalance-portfolio-42',
});
// Report task outcomes directly
client.reportOutcome('task-123', true, {
durationMs: 2400,
cost: 0.05,
metadata: { pnl: 12.50 },
});Manual Tracking
For non-Express frameworks or custom tracking:
import { createAnalytix402Client } from '@analytix402/sdk';
const client = createAnalytix402Client({
apiKey: 'ax_live_xxxxx',
});
// Track a custom event
client.track({
type: 'request',
method: 'GET',
path: '/api/data',
statusCode: 200,
responseTimeMs: 45,
timestamp: new Date().toISOString(),
payment: {
amount: '0.01',
currency: 'USDC',
wallet: '0x8f2a...',
status: 'success',
},
});
// Flush events before shutdown
await client.flush();
// Graceful shutdown
await client.shutdown();Proxy URL Integration
Instead of the SDK middleware, you can route API calls through Analytix402's proxy:
https://analytix402.com/api/p/{your-api-slug}/your/endpointPass your spend key as a header:
const response = await fetch(
'https://analytix402.com/api/p/weather-api/forecast?city=NYC',
{
headers: {
'X-Spend-Key': 'sk_live_your_spend_key',
},
}
);The proxy handles payment, analytics tracking, and circuit breaker enforcement automatically.
Performance
- < 50ms overhead per request
- Events are batched and sent asynchronously
- Automatic retry with exponential backoff
- Offline queue (up to 1000 events)
- Non-blocking — your API never waits for Analytix402
Requirements
- Node.js 18+
- Express 4.x or 5.x (for middleware, optional)
License
MIT
