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

@mastra/posthog

v1.0.8

Published

PostHog observability provider for Mastra

Downloads

28,475

Readme

@mastra/posthog

PostHog AI Observability exporter for Mastra applications.

Installation

npm install @mastra/posthog

Usage

Zero-Config Setup

The exporter automatically reads credentials from environment variables:

# Required
POSTHOG_API_KEY=phc_...

# Optional
POSTHOG_HOST=https://us.i.posthog.com  # or eu.i.posthog.com
import { PosthogExporter } from '@mastra/posthog';

const mastra = new Mastra({
  ...,
  observability: {
    configs: {
      posthog: {
        serviceName: 'my-service',
        exporters: [new PosthogExporter()],
      },
    },
  },
});

Explicit Configuration

You can also pass credentials directly:

import { PosthogExporter } from '@mastra/posthog';

const mastra = new Mastra({
  ...,
  observability: {
    configs: {
      posthog: {
        serviceName: 'my-service',
        exporters: [
          new PosthogExporter({
            apiKey: 'phc_...',
            host: 'https://us.i.posthog.com', // optional, defaults to US region
          }),
        ],
      },
    },
  },
});

Features

AI Tracing

  • Event-based architecture: Captures LLM calls and operations as PostHog events
  • LLM analytics: Automatic tracking of token usage, latency, and costs
  • Streaming support: Handles streaming LLM responses with MODEL_CHUNK events
  • Privacy mode: Optional exclusion of input/output data for sensitive applications
  • Serverless optimized: Auto-configures batching for serverless environments

Supported Event Types

  • $ai_generation: LLM model calls (MODEL_GENERATION, MODEL_STEP)
  • $ai_span: Operations like tool calls, workflows, and streaming chunks
  • Hierarchical traces with parent-child relationships via $ai_parent_id
  • Session grouping with $ai_session_id

Configuration

Basic Configuration

new PosthogExporter({
  apiKey: process.env.POSTHOG_API_KEY,
});

Advanced Configuration

new PosthogExporter({
  // Required
  apiKey: process.env.POSTHOG_API_KEY,

  // Optional: Region/Host
  host: 'https://eu.i.posthog.com', // EU region
  // or
  host: 'https://your-instance.com', // Self-hosted

  // Optional: Batching (defaults: flushAt=20, flushInterval=10000)
  flushAt: 20, // Batch size before auto-flush
  flushInterval: 10000, // Flush interval in milliseconds

  // Optional: Serverless mode (auto-configures smaller batches)
  serverless: true, // Sets flushAt=10, flushInterval=2000

  // Optional: User identification
  defaultDistinctId: 'anonymous', // Fallback if no userId in metadata

  // Optional: Privacy
  enablePrivacyMode: false, // Set to true to exclude input/output from LLM events
});

Serverless Environments

When deploying to serverless environments (Lambda, Vercel Functions, etc.), enable serverless mode:

new PosthogExporter({
  apiKey: process.env.POSTHOG_API_KEY,
  serverless: true, // Auto-configures for serverless
});

Important: Always call await mastra.shutdown() before your serverless function exits to flush remaining events.

Privacy Mode

To exclude sensitive input/output data while still tracking token usage and latency:

new PosthogExporter({
  apiKey: process.env.POSTHOG_API_KEY,
  enablePrivacyMode: true, // Excludes $ai_input and $ai_output_choices
});

Note: Privacy mode only applies to $ai_generation events. Span events (tool calls, etc.) still include input/output state.

Metadata

Include metadata in your Mastra spans to enrich PostHog events:

// User identification
{
  metadata: {
    userId: 'user-123',      // → distinctId in PostHog
    sessionId: 'session-abc', // → $ai_session_id for grouping

    // Custom properties (passed through to PostHog)
    environment: 'production',
    version: '1.0.0',
  }
}

Cost Tracking

PostHog automatically calculates costs from:

  • Model name + token counts (uses OpenRouter pricing data)
  • Or you can send pre-calculated costs in span attributes

Viewing Data in PostHog

  1. Navigate to Product AnalyticsEvents
  2. Filter for events starting with $ai_
  3. Use the AI Observability dashboard (if available in your PostHog plan)
  4. Query events by:
    • $ai_trace_id: Group all events in a trace
    • $ai_session_id: Group traces in a session
    • $ai_model: Filter by model (e.g., "gpt-4o")
    • $ai_provider: Filter by provider (e.g., "openai")

Environment Variables

# Required
POSTHOG_API_KEY=phc_...

# Optional
POSTHOG_HOST=https://us.i.posthog.com  # or eu.i.posthog.com

Links