npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

apianalytics-hono

v0.1.16

Published

High-performance API Analytics middleware for Hono

Readme

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 key
  • privacyLevel (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 server
  • sampleRate (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

  1. 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
    })
  2. Configure Privacy Level: Choose appropriate privacy settings for your use case:

    analytics({
      apiKey: 'your-api-key',
      privacyLevel: 2, // Never send IP addresses
    })
  3. 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
    })
  4. 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