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 🙏

© 2025 – Pkg Stats / Ryan Hefner

nestjs-mixpanel

v1.5.0

Published

NestJS Mixpanel integration module

Readme

NestJS Mixpanel

A powerful NestJS module for seamless Mixpanel analytics integration with automatic user identification and request context management.

Features

  • Easy Integration - Simple setup with NestJS dependency injection
  • Flexible User Identification - Multiple strategies for automatic user tracking
  • Request Context Management - Built-in AsyncLocalStorage for request isolation
  • Dynamic Data Access - Real-time access to request, session, and user data
  • TypeScript Support - Fully typed with TypeScript definitions
  • Well Tested - Comprehensive test suite with unit, integration, and e2e tests

Installation

npm install nestjs-mixpanel
# or
yarn add nestjs-mixpanel
# or
pnpm add nestjs-mixpanel

Quick Start

import { Module } from '@nestjs/common';
import { MixpanelModule } from 'nestjs-mixpanel';

@Module({
  imports: [
    MixpanelModule.forRoot({
      token: 'YOUR_MIXPANEL_TOKEN',
    }),
  ],
})
export class AppModule {}
import { Injectable } from '@nestjs/common';
import { MixpanelService } from 'nestjs-mixpanel';

@Injectable()
export class AnalyticsService {
  constructor(private readonly mixpanel: MixpanelService) {}

  trackUserAction(action: string, properties?: any) {
    this.mixpanel.track(action, properties);
  }
}

Configuration Options

User Identification Strategies

The module provides multiple strategies to automatically identify users:

1. AsyncStorage Context ID (Default)

If no identification strategy is specified, the module will use a unique ID from the AsyncLocalStorage context:

MixpanelModule.forRoot({
  token: 'YOUR_MIXPANEL_TOKEN',
  // Will use AsyncLocalStorage context ID as distinct_id
})

2. Header-based Identification

Extract user ID from HTTP headers:

MixpanelModule.forRoot({
  token: 'YOUR_MIXPANEL_TOKEN',
  header: 'x-user-id', // Will look for user ID in this header
})

3. Session-based Identification

Extract user ID from session object using dot notation:

MixpanelModule.forRoot({
  token: 'YOUR_MIXPANEL_TOKEN',
  session: 'user.id', // Will extract from req.session.user.id
})

4. User Object-based Identification

Extract user ID from user object using dot notation:

MixpanelModule.forRoot({
  token: 'YOUR_MIXPANEL_TOKEN',
  user: 'profile.userId', // Will extract from req.user.profile.userId
})

5. Cookie-based Identification

Extract user ID from cookies (requires cookie-parser):

// First, install and configure cookie-parser in your application

// main.ts
import cookieParser from 'cookie-parser';
app.use(cookieParser());

// Then configure MixpanelModule
MixpanelModule.forRoot({
  token: 'YOUR_MIXPANEL_TOKEN',
  cookie: 'userId', // Will extract from req.cookies.userId
})

Additional Configuration

IP Address Tracking

The module can automatically extract client IP addresses from request headers for geolocation:

MixpanelModule.forRoot({
  token: 'YOUR_MIXPANEL_TOKEN',
  ipHeader: 'X-Forwarded-For', // Default, can also use 'X-Real-IP' or 'Forwarded'
})

Supported headers:

  • X-Forwarded-For (default) - Standard proxy header, uses the first IP if multiple
  • X-Real-IP - Common nginx header
  • Forwarded - RFC 7239 standard header

The IP address is automatically included in all track events and profile updates for geolocation data.

API Reference

MixpanelService

track(event: string, properties?: Mixpanel.PropertyDict, callback?: Mixpanel.Callback): void

Tracks an event in Mixpanel with automatic user identification.

// Basic event tracking
this.mixpanel.track('page_viewed');

// With custom properties
this.mixpanel.track('purchase_completed', {
  amount: 99.99,
  currency: 'USD',
  items: ['item1', 'item2'],
});

// With callback
this.mixpanel.track('purchase_completed', {
  amount: 99.99,
}, (err) => {
  if (err) {
    console.error('Failed to track event:', err);
  }
});

The distinct_id is automatically set based on your configured identification strategy.

people.set(distinctId: string, properties: Mixpanel.PropertyDict, modifiers?: Mixpanel.Modifiers, callback?: Mixpanel.Callback): void

people.set(properties: Mixpanel.PropertyDict, modifiers?: Mixpanel.Modifiers, callback?: Mixpanel.Callback): void

Sets properties on a user profile. Can be called with or without a specific user ID.

// With explicit user ID
this.mixpanel.people.set('user-123', {
  name: 'John Doe',
  email: '[email protected]',
  plan: 'premium',
});

// With automatic user identification
this.mixpanel.people.set({
  name: 'John Doe',
  email: '[email protected]',
  plan: 'premium',
});

// With callback
this.mixpanel.people.set({
  name: 'John Doe',
}, (err) => {
  if (err) console.error('Failed to set properties:', err);
});

// With modifiers (e.g., custom IP or location)
this.mixpanel.people.set({
  name: 'John Doe',
}, {
  $ip: '192.168.1.1',
  $latitude: 40.7128,
  $longitude: -74.0060,
});

people.setOnce(distinctId: string, properties: Mixpanel.PropertyDict, modifiers?: Mixpanel.Modifiers, callback?: Mixpanel.Callback): void

people.setOnce(properties: Mixpanel.PropertyDict, modifiers?: Mixpanel.Modifiers, callback?: Mixpanel.Callback): void

Sets properties on a user profile only if they are not already set.

// With automatic user identification
this.mixpanel.people.setOnce({
  created_at: new Date().toISOString(),
  initial_source: 'organic',
});

// With explicit user ID
this.mixpanel.people.setOnce('user-123', {
  created_at: new Date().toISOString(),
});

// With callback
this.mixpanel.people.setOnce({
  created_at: new Date().toISOString(),
}, (err) => {
  if (err) console.error('Failed to set properties:', err);
});

// With modifiers
this.mixpanel.people.setOnce({
  created_at: new Date().toISOString(),
}, {
  $ignore_time: true,
});

extractUserId(): string | undefined

Internal method that extracts the user ID based on the configured identification strategy. Returns the extracted user ID or falls back to the AsyncLocalStorage context ID.

Advanced Usage

Custom User Identification

You can override the automatic user identification by providing a distinct_id in the properties:

this.mixpanel.track('custom_event', {
  distinct_id: 'custom-user-123',
  customProp: 'value',
});

Request Context

The module uses AsyncLocalStorage to maintain request context automatically. This ensures that:

  • Each request has its own isolated context
  • User identification works correctly across async operations
  • No memory leaks between requests
  • Guards and middleware can dynamically set user/session data

Development

Building

pnpm build        # Build the project
pnpm dev          # Build in watch mode

Testing

pnpm test         # Run tests
pnpm test:watch   # Run tests in watch mode
pnpm test:coverage # Run tests with coverage
pnpm test:ui      # Open test UI

Requirements

  • Node.js >= 20.0.0
  • NestJS >= 11.0.0