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

supertokentracker

v1.0.4

Published

Google Gemini token tracker that automatically logs prompts, responses, and token usage

Readme

supertokentracker

Automatically track Google Gemini token usage with built-in logging and analytics

Track every Gemini API call with zero configuration. Perfect for monitoring usage, debugging, cost analysis, and building analytics.

Features

Automatic Tracking - Drop-in replacement for @google/genaiBackward Compatible - Works with code written for legacy @google/generative-aiLocal Storage - Save to JSON files on your machine ✅ Cloud Storage - Optional cloud sync with tokentracker.dev (coming soon) ✅ Full Request Data - Captures prompts, responses, token usage, and errors ✅ Stream Support - Works with both generateContent and generateContentStreamTypeScript - Full type safety included

Installation

npm install supertokentracker @google/genai

Quick Start

Local Storage (JSON File)

import { TokenTracker } from "supertokentracker";

const tracker = new TokenTracker({
  apiKey: process.env.GEMINI_API_KEY,
});

const response = await tracker.models.generateContent({
  model: "gemini-2.5-flash",
  contents: "Explain quantum computing in 3 sentences",
});

console.log(response.text);

// Get all tracked requests
const history = await tracker.getTrackedRequests();
console.log(`Total requests: ${history.length}`);
console.log(`Tokens used: ${history[0].usage?.totalTokens}`);

Data is automatically saved to ./gemini-tracker-logs.json.

Cloud Storage (Coming Soon)

Sync your tracking data to the cloud for team analytics and dashboards:

import { TokenTracker } from "supertokentracker";

const tracker = new TokenTracker({
  apiKey: process.env.GEMINI_API_KEY,
  remoteStorage: {
    apiKey: "your-tokentracker-api-key", // Get from tokentracker.dev
    projectName: "my-project",
  },
});

const response = await tracker.models.generateContent({
  model: "gemini-2.5-flash",
  contents: "Hello world",
});

Sign up at tokentracker.dev to get your API key and access the analytics dashboard.

Configuration

TrackerOptions

interface TrackerOptions {
  // Gemini API credentials
  apiKey?: string;
  apiVersion?: string;
  location?: string;
  project?: string;
  vertexai?: boolean;

  // Storage mode (optional - inferred from config if omitted)
  storage?: "local" | "file" | "remote";

  // File storage options
  localStorage?: {
    filePath?: string; // Default: './gemini-tracker-logs.json'
    autoSave?: boolean; // Default: true
  };
  fileStorage?: {
    filePath?: string;
    autoSave?: boolean;
  };

  // Remote storage options
  remoteStorage?: {
    endpoint?: string; // Default: https://api.tokentracker.dev/api/track
    apiKey: string; // Your API key for authentication
    projectName?: string;
    timeout?: number; // Default: 10000ms
    retries?: number; // Default: 3
    retryDelay?: number; // Default: 1000ms (exponential backoff)
  };
}

// If `remoteStorage` is provided the tracker will automatically use cloud storage.
// If `fileStorage` (or legacy `localStorage`) is provided the tracker uses file storage.
// You can still set `storage` explicitly to override the default behaviour.

What Gets Tracked

Every request captures:

{
  id: "uuid-v4",
  timestamp: "2025-10-17T10:30:00.000Z",
  model: "gemini-2.5-flash",
  prompt: { /* your input */ },
  response: { /* full API response */ },
  usage: {
    promptTokens: 7,
    completionTokens: 15,
    totalTokens: 22
  },
  error: null  // or error details if request failed
}

API Methods

getTrackedRequests()

Retrieve all tracked requests (local or remote):

const requests = await tracker.getTrackedRequests();

loadHistory() (Local only)

Load previously saved requests from disk:

await tracker.loadHistory();

saveHistory() (Local only)

Manually save tracked requests to disk:

await tracker.saveHistory();

clearHistory()

Clear all tracked requests from memory:

tracker.clearHistory();

Use Cases

1. Development Debugging

Track all requests during development to debug prompts and responses.

2. Cost Monitoring

Analyze token usage to optimize costs:

const history = await tracker.getTrackedRequests();
const totalTokens = history.reduce(
  (sum, req) => sum + (req.usage?.totalTokens || 0),
  0
);
console.log(`Total tokens used: ${totalTokens}`);

3. Analytics Dashboard

Build usage dashboards with tracked data:

  • Requests per day
  • Average response time
  • Most used models
  • Token consumption trends

4. Multi-tenant SaaS

Track usage per customer with cloud storage:

  • Monitor API usage across your customer base
  • Implement usage-based billing
  • Set limits per subscription tier

Error Handling

The tracker gracefully handles storage failures without breaking your app:

// If storage fails, the API call still succeeds
const response = await tracker.models.generateContent({...});
// Response is returned even if tracking fails

Failed storage attempts are logged to console.error but don't throw exceptions.

Stream Support

Streaming responses are fully supported:

const stream = await tracker.models.generateContentStream({
  model: "gemini-2.5-flash",
  contents: "Write a story",
});

for await (const chunk of stream) {
  process.stdout.write(chunk.text);
}

// Full response is tracked after stream completes

TypeScript

Full type definitions included:

import {
  TokenTracker,
  TrackedRequest,
  TrackerOptions,
  StorageMode,
} from "supertokentracker";

Backward Compatibility

This package wraps the new @google/genai SDK but maintains full backward compatibility with code written for the legacy @google/generative-ai SDK.

Both access patterns work:

const result = await tracker.models.generateContent({...});

// ✅ NEW SDK style (@google/genai)
console.log(result.candidates);
console.log(result.usageMetadata);

// ✅ OLD SDK style (@google/generative-ai) - ALSO WORKS!
console.log(result.response.candidates);
console.log(result.response.usageMetadata);

This means you can:

  • Migrate from @google/generative-ai without changing your code
  • Use code examples from either SDK documentation
  • Mix both access patterns in the same project

Note: The legacy @google/generative-ai package is deprecated and support ends August 31, 2025. This tracker helps you migrate to the new SDK while maintaining compatibility with your existing code.

Contributing

Contributions welcome! Please open an issue or PR.

License

MIT

Links