0.1.16 • Published 5 months ago
apianalytics-hono v0.1.16
API Analytics for Hono
High-performance API analytics middleware for Hono, designed for production use with features like request batching, sampling, retries, and privacy controls.
Features
- 🚀 High Performance: Non-blocking analytics with minimal overhead
- 📊 Smart Batching: Configurable batch sizes and flush intervals
- 🎯 Request Sampling: Control analytics volume with sampling rates
- 🔄 Automatic Retries: Exponential backoff for failed requests
- 🔒 Privacy Controls: Configurable IP address handling
- 📈 Runtime Metrics: Optional collection of memory usage
- ⚡ Edge Ready: Works in any environment (Node.js, Bun, Deno, Edge)
- 🔍 Debug Mode: Detailed logging for troubleshooting
- 💾 Memory Efficient: WeakMap-based client management
Installation
npm install apianalytics-hono
# or
bun add apianalytics-hono
Quick Start
import { Hono } from 'hono';
import { analytics } from 'apianalytics-hono';
const app = new Hono();
// Add the middleware
app.use('*', analytics({
apiKey: 'your-api-key',
// Optional configuration
privacyLevel: 0,
serverUrl: 'https://your-analytics-server.com',
sampleRate: 1.0,
batchSize: 100,
flushInterval: 60,
debug: false,
}));
// Your routes
app.get('/', (c) => c.text('Hello World!'));
export default app;
Configuration
Basic Options
apiKey
(required): Your API Analytics API keyprivacyLevel
(optional): Controls client identification by IP address- 0: Sends client IP to be stored and location inferred (default)
- 1: Sends IP only for location inference, then discards
- 2: Never sends IP address
serverUrl
(optional): For self-hosting, points to your analytics serversampleRate
(optional): Percentage of requests to log (0.0-1.0, default: 1.0)batchSize
(optional): Maximum requests per batch (default: 100)flushInterval
(optional): Seconds between forced flushes (default: 60)retryAttempts
(optional): Number of retry attempts for failed requests (default: 3)timeout
(optional): Request timeout in milliseconds (default: 5000)debug
(optional): Enable debug logging (default: false)collectRuntimeMetrics
(optional): Collect memory usage metrics (default: false)
Advanced Options
Custom Mappers
app.use('*', analytics({
apiKey: 'your-api-key',
mappers: {
getUserId: (c) => c.req.header('x-api-key'),
getPath: (c) => c.req.path,
getIpAddress: (c) => c.req.header('x-real-ip'),
getHostname: (c) => c.req.header('host'),
getUserAgent: (c) => c.req.header('user-agent'),
getHeaders: (c) => ({ 'content-type': c.req.header('content-type') }),
getQueryParams: (c) => Object.fromEntries(new URL(c.req.url).searchParams),
},
}));
Header Collection
app.use('*', analytics({
apiKey: 'your-api-key',
includeHeaders: ['content-type', 'accept'],
}));
Best Practices
Set Appropriate Sample Rate: For high-traffic APIs, use sampling to reduce analytics volume:
analytics({ apiKey: 'your-api-key', sampleRate: 0.1, // Log 10% of requests })
Configure Privacy Level: Choose appropriate privacy settings for your use case:
analytics({ apiKey: 'your-api-key', privacyLevel: 2, // Never send IP addresses })
Optimize Batch Size: Adjust based on your traffic patterns:
analytics({ apiKey: 'your-api-key', batchSize: 50, // Smaller batches for lower latency flushInterval: 30, // More frequent flushes })
Enable Debug Mode in Development:
analytics({ apiKey: 'your-api-key', debug: process.env.NODE_ENV !== 'production', })
Development
# Install dependencies
npm install
# Build
npm run build
# Run tests
npm test
# Run benchmarks
npm run benchmark
# Check types
npm run typecheck
# Format code
npm run format
# Lint
npm run lint
Performance Impact
The middleware is designed to have minimal impact on your API's performance:
- Non-blocking analytics processing
- Efficient request batching
- Configurable sampling
- Memory-efficient client management
- Zero dependencies
License
MIT