JavaScript SDK for tracking and monitoring API calls in web applications. Get real-time analytics and insights.
npm install zamizayn-api-tracker-sdkA lightweight, zero-dependency SDK for tracking API calls on websites. Easily monitor all HTTP requests made by your application with minimal configuration.
- 🚀 Zero Dependencies - Lightweight and fast
- 📊 Comprehensive Tracking - Track fetch and XMLHttpRequest calls
- ⚙️ Highly Configurable - Fine-tune what gets tracked
- 🔒 Privacy-Focused - Exclude sensitive headers and data
- 📦 Multiple Formats - UMD, ESM, and CommonJS builds
- 💪 TypeScript Support - Full type definitions included
- 🎯 Selective Tracking - Whitelist/blacklist URLs with regex patterns
- 📈 Batching & Sampling - Optimize performance with batching and sampling
``bash`
npm install api-tracker-sdk
`html`
`javascript
import { initTracker } from 'api-tracker-sdk';
// Initialize the tracker
const tracker = initTracker({
endpoint: 'https://your-backend.com/api/tracking',
projectId: 'my-website',
enabled: true,
});
// That's it! All API calls are now being tracked
`
`html`
`typescript`
interface TrackerConfig {
// Required: Endpoint where tracking data will be sent
endpoint: string;
// Optional: Unique identifier for your project
projectId?: string;
// Optional: Enable/disable tracking (default: true)
enabled?: boolean;
// Optional: Sample rate 0-1 (default: 1 = track all requests)
sampleRate?: number;
// Optional: Only track URLs matching these patterns
includeUrls?: RegExp[];
// Optional: Exclude URLs matching these patterns
excludeUrls?: RegExp[];
// Optional: Track request headers (default: true)
trackRequestHeaders?: boolean;
// Optional: Track response headers (default: true)
trackResponseHeaders?: boolean;
// Optional: Track request body (default: false)
trackRequestBody?: boolean;
// Optional: Track response body (default: false)
trackResponseBody?: boolean;
// Optional: Headers to exclude (default: ['authorization', 'cookie', 'set-cookie'])
excludeHeaders?: string[];
// Optional: Max body size to track in bytes (default: 10000)
maxBodySize?: number;
// Optional: Batch size before sending (default: 10)
batchSize?: number;
// Optional: Auto-flush interval in ms (default: 30000)
flushInterval?: number;
// Optional: Enable debug logging (default: false)
debug?: boolean;
// Optional: Custom metadata attached to all events
metadata?: Record
}
`javascript
import { initTracker } from 'api-tracker-sdk';
initTracker({
endpoint: 'https://analytics.example.com/track',
projectId: 'my-app',
});
`
`javascript`
initTracker({
endpoint: 'https://analytics.example.com/track',
includeUrls: [
/^https:\/\/api\.example\.com/,
/^https:\/\/backend\.example\.com/,
],
});
`javascript`
initTracker({
endpoint: 'https://analytics.example.com/track',
excludeUrls: [
/localhost/,
/127\.0\.0\.1/,
/internal\.example\.com/,
],
});
`javascript`
initTracker({
endpoint: 'https://analytics.example.com/track',
sampleRate: 0.5, // Track only 50% of requests
});
`javascript`
initTracker({
endpoint: 'https://analytics.example.com/track',
trackRequestBody: true,
trackResponseBody: true,
maxBodySize: 5000, // Limit body size to 5KB
});
`javascript`
initTracker({
endpoint: 'https://analytics.example.com/track',
metadata: {
environment: 'production',
version: '1.2.3',
userId: 'user-123',
},
});
`javascript`
initTracker({
endpoint: 'https://analytics.example.com/track',
debug: true, // Enable console logging
});
`javascript
import { initTracker, getTracker, destroyTracker } from 'api-tracker-sdk';
// Initialize
const tracker = initTracker({ endpoint: '...' });
// Manually flush queued events
tracker.flush();
// Update configuration
tracker.updateConfig({ sampleRate: 0.5 });
// Check if active
if (tracker.isActive()) {
console.log('Tracker is running');
}
// Destroy tracker
destroyTracker();
`
`jsx
import { useEffect } from 'react';
import { initTracker, destroyTracker } from 'api-tracker-sdk';
function App() {
useEffect(() => {
const tracker = initTracker({
endpoint: 'https://analytics.example.com/track',
projectId: 'my-react-app',
});
return () => {
destroyTracker();
};
}, []);
return
Data Format
$3
Each tracked API call generates an event with this structure:
`typescript
{
projectId: "my-website",
request: {
id: "1234567890-abc123",
timestamp: 1234567890000,
url: "https://api.example.com/users",
method: "GET",
headers: { "content-type": "application/json" },
body: "...",
size: 1024
},
response: {
requestId: "1234567890-abc123",
status: 200,
statusText: "OK",
headers: { "content-type": "application/json" },
body: "...",
size: 2048,
duration: 234,
success: true
},
metadata: { ... },
userAgent: "Mozilla/5.0 ...",
pageUrl: "https://example.com/page"
}
`$3
Events are sent in batches:
`typescript
{
events: [ / array of tracking events / ],
timestamp: 1234567890000,
sessionId: "session-abc123"
}
`Backend Integration
Your backend endpoint should accept POST requests with the batch format:
`javascript
// Express.js example
app.post('/api/tracking', (req, res) => {
const batch = req.body;
console.log(Received ${batch.events.length} events);
console.log(Session: ${batch.sessionId});
// Process events (save to database, analytics, etc.)
batch.events.forEach(event => {
console.log(${event.request.method} ${event.request.url} - ${event.response.status});
});
res.json({ success: true });
});
`Browser Compatibility
- Chrome/Edge: ✅ Full support
- Firefox: ✅ Full support
- Safari: ✅ Full support
- IE11: ❌ Not supported (uses modern APIs)
Performance Considerations
1. Batching: Events are batched to reduce network overhead
2. Sampling: Use
sampleRate to track a percentage of requests
3. Body Tracking: Disable body tracking for better performance
4. Selective Tracking: Use includeUrls/excludeUrls to track only relevant APIsPrivacy & Security
- Sensitive headers (Authorization, Cookie) are excluded by default
- Request/response bodies are NOT tracked by default
- Configure
excludeHeaders to remove additional sensitive data
- Use maxBodySize` to limit data collectionMIT
For issues and questions, please open an issue on GitHub.