NPM Star
Collections
  1. Home
  2. Compare
  3. amplitude vs mixpanel
NPM Compare

Compare NPM packages statistics, trends, and features

CollectionsVS Code extensionChrome extensionTermsPrivacyLinkTreeIndiehackersBig Frontendqiuyumi

Unable to load comparison data. Please try again later.

amplitude

Node CI Known Vulnerabilities

Server side implementation of Amplitude's HTTP API.

Amplitude SSL Issue

As of 2020-05-30, Amplitude reported issues with their SSL certificate, so they set up an endpoint and alternate endpoint at https://api2.amplitude.com. Read about it on Amplitude's Status Page and affected devices here.

As of v5.1.0+, you can use the alternative endpoint by setting the environment variable:

AMPLITUDE_TOKEN_ENDPOINT = 'https://api2.amplitude.com'

Or in the constructor:

const amplitude = new Amplitude('api-token', { tokenEndpoint: 'https://api2.amplitude.com' })

Version 5+ Note

For amplitude@5+, it uses Amplitude's V2 HTTP API, which replaces the deprecated V1 HTTP API. This only affects the .track method. The only potential breaking change is by default user_id and device_id require a minimum of 5 characters.

Install

npm install amplitude --save

Basic Initialization

const Amplitude = require('amplitude') // The only required field is the api token const amplitude = new Amplitude('api-token')

See the examples/ directory for further usage.

Track an event

Pass in any keys listed on the Amplitude V2 HTTP API. The only required keys are event_type and either user_id or device_id. If you initialized the Amplitude object with a user/device id, they can be ignored when calling the track method. Note: the user_id and device_id must be 5 or more characters if passed.

const data = { event_type: 'some value', // required user_id: 'some-user-id', // only required if device id is not passed in device_id: 'some-device-id', // only required if user id is not passed in session_id: 1492789357923, // must be unix timestamp in ms, not required event_properties: { //... }, user_properties: { //... } } try { await amplitude.track(data) } catch (err) { console.error(err) }

You can also pass an array of event objects:

const data = [ { event_type: 'some value', // required user_id: 'some id', // only required if device id is not passed in device_id: 'some id', // only required if user id is not passed in event_properties: { //... }, user_properties: { //... } }, { event_type: 'another value', // required user_id: 'some id', // only required if device id is not passed in device_id: 'some id', // only required if user id is not passed in event_properties: { //... }, user_properties: { //... } } ] amplitude.track(data).then(res => { console.log('Amplitude response', res) })

Identify API

The identify method allows you to make changes to a user without sending an analytics event.

const data = { user_id: 'some id', // only required if device id is not passed in device_id: 'some id', // only required if user id is not passed in event_properties: { //... }, user_properties: { //... } } amplitude.identify(data).then(res => { console.log('Amplitude response', res) })

You can also pass an array of identify objects:

const data = [ { user_id: 'some id', // only required if device id is not passed in device_id: 'some id', // only required if user id is not passed in event_properties: { //... }, user_properties: { //... } }, { user_id: 'some id', // only required if device id is not passed in device_id: 'some id', // only required if user id is not passed in event_properties: { //... }, user_properties: { //... } } ] amplitude.identify(data).then(res => { console.log('Amplitude response', res) })

With this method, you can also modify user properties using property operations.

const data = { user_id: 'some id', // only required if device id is not passed in device_id: 'some id', // only required if user id is not passed in user_properties: { $set: { //... }, $add: { //... }, $append: { //... } } } amplitude.identify(data).then(res => { console.log('Amplitude response', res) })

Note the limitation of mixing user property operations with top level properties. If you use any property operations ($add, $append, etc.), and you want to set a user property, it must be done using the $set operation.

CamelCase Data

If you prefer camelCase variables, you can pass in the camelCase version instead to the track and identify methods:

const data = { eventType: 'some value', // required userId: 'some id', // only required if device id is not passed in deviceId: 'some id', // only required if user id is not passed in sessionId: 1492789357923, // must be unix timestamp in ms, not required eventProperties: { //... }, userProperties: { //... } } amplitude.track(data).then(res => { console.log('Amplitude response', res) })

This is the full list of properties that will be automatically transformed:

userId -> user_id
deviceId -> device_id
sessionId -> session_id
eventType -> event_type
eventProperties -> event_properties
userProperties -> user_properties
appVersion -> app_version
osName -> os_name
osVersion -> os_version
deviceBrand -> device_brand
deviceManufacturer -> device_manufacturer
deviceModel -> device_model
locationLat -> location_lat
locationLng -> location_lng

User/Device/Session ID

If the user/device/session id will always be the same, you can initialize the object with it. Passing a user id or device id in the track and identify methods will override the default value set at initialization.

const amplitude = new Amplitude('api-token', { user_id: 'some-user-id' }) // or const amplitude = new Amplitude('api-token', { device_id: 'some-device-id' }) // or const amplitude = new Amplitude('api-token', { session_id: 1492789357923 }) try { await amplitude.track({ event_type: 'some value' }) } catch (err) { console.error(err) } // Or... amplitude .track({ event_type: 'some value', user_id: 'will-override-the-default-id' }) .then(res => { console.log('Amplitude response', res) })

Promises

All methods return a Promise.

amplitude .track(data) .then(function(result) { //... do something }) .catch(function(error) { //... do something }) // Or.. try { const result = await amplitude.track({ event_type: 'some value' }) //... do something with result } catch (error) { console.error(error) //... do something with the error }

Dashboard API

Export your data

The export method requires your secret key to be added when initializing the amplitude object. This method uses the export api and requires a start and end string in the format YYYYMMDDTHH.

The method returns a stream.

const fs = require('fs') const stream = fs.createWriteStream('./may-2016-export.zip') const amplitude = new Amplitude('api-token', { secretKey: 'secret' }) amplitude .export({ start: '20160501T20', end: '20160601T20' }) .pipe(stream)

User Search

The user search method requires your secret key to be added when initializing the amplitude object. This method uses the dashboard api.

Search for a user with a specified Amplitude ID, Device ID, User ID, or User ID prefix.

const amplitude = new Amplitude('api-token', { secretKey: 'secret' }) amplitude.userSearch('user/device/amplitude id or user id prefix').then(res => { const matches = res.matches // Array of matches // How the match was made // If exact match was made with user id or device id, type === 'match_user_or_device_id' // If exact match was made with Amplitude ID, type === 'match_amplitude_id' // If a partial match was made with a user id prefix, type === 'match_user_prefix' // If no match was made, type === 'nomatch' const type = res.type })

User Activity

The user activity method requires your secret key to be added when initializing the amplitude object. This method uses the dashboard api.

Get a user summary and their recent events. This method requires an Amplitude ID. You can use the user search method to find that.

const amplitude = new Amplitude('api-token', { secretKey: 'secret' }) amplitude.userActivity('Amplitude ID').then(function(res) { const userData = res.userData // data about the user const events = res.events // an array of events associated with the user })

If there is nothing found for the passed Amplitude ID, the Promise will still resolve. The userData object will contain empty values and the events array will be empty:

{ userData: { num_sessions: 0, purchases: 0, revenue: 0, merged_amplitude_ids: [], num_events: 0, canonical_amplitude_id: 1, user_id: null, last_location: null, usage_time: 0, last_device_id: null, device_ids: [] }, events: [] }

If you do not know the Amplitude ID, you can use the userSearch method to find it.

const amplitude = new Amplitude('api-token', { secretKey: 'secret' }) amplitude .userSearch('user-id') .then(function(res) { // If you're using a prefix, you may get multiple matches and // you may need to handle the case where there is not a match const match = res.matches[0] return amplitude.userActivity(match.amplitude_id) }) .then(function(res) { const userData = res.userData // data about the user const events = res.events // an array of events associated with the user })

Event Segmentation

The event segmentation method requires your secret key to be added when initializing the amplitude object. This method uses the dashboard api.

Get metrics for an event with segmentation.

const amplitude = new Amplitude('api-token', { secretKey: 'secret' }) amplitude .eventSegmentation({ e: { event_type: 'event_name' }, start: '20170104', end: '20170117' }) .then(res => { const segmentationData = res.data })

Example response:

{ series: [ [ 2, 25, 3, 1, 0, 0, 2, 3, 5, 1, 0, 0, 0, 0 ] ], seriesLabels: [ 0 ], xValues: [ '2017-01-04', '2017-01-05', '2017-01-06', '2017-01-07', '2017-01-08', '2017-01-09', '2017-01-10', '2017-01-11', '2017-01-12', '2017-01-13', '2017-01-14', '2017-01-15', '2017-01-16', '2017-01-17' ] }

If the event does not exist, Amplitude will throw a 400 error.

Changelog

View the CHANGELOG for changes in each version.

<!--- Do not change anything below this comment. It is generated automatically. ------>

Contributors

  • Erki Esken
  • Matthew Keesan
  • Geoff Dutton
  • Matt Pardee
  • Chase Seibert
  • filip

Mixpanel-node

July 29, 2026 - v0.23.0

Build Status

This library provides many of the features in the official JavaScript mixpanel library. It is easy to use, and fully async. It is intended to be used on the server (it is not a client module). The in-browser client library is available at https://github.com/mixpanel/mixpanel-js.

Repository structure

This repository is an npm workspace with two packages under packages/:

  • packages/mixpanel — the mixpanel SDK published to npm (this readme).
  • packages/openfeature-server-provider — the @mixpanel/openfeature-server-provider package, an OpenFeature server-side provider backed by Mixpanel feature flags.

Installation

npm install mixpanel

Quick Start

// grab the Mixpanel factory var Mixpanel = require("mixpanel"); // create an instance of the mixpanel client var mixpanel = Mixpanel.init("<YOUR_TOKEN>"); // for server-side integrations requiring authentication (e.g., importing old events), // use service account credentials for enhanced security const { ServiceAccountCredentials } = Mixpanel; const credentials = new ServiceAccountCredentials( "YOUR_SERVICE_ACCOUNT_USERNAME", "YOUR_SERVICE_ACCOUNT_SECRET", "YOUR_PROJECT_ID", ); var mixpanel = Mixpanel.init("<YOUR_TOKEN>", { credentials }); // initialize mixpanel client configured to communicate over http instead of https var mixpanel = Mixpanel.init("<YOUR_TOKEN>", { protocol: "http", }); // turn off keepAlive (reestablish connection on each request) var mixpanel = Mixpanel.init("<YOUR_TOKEN>", { keepAlive: false, }); // pass the custom logger (default is console) var mixpanel = Mixpanel.init("<YOUR_TOKEN>", { debug: true, logger: pinoLogger, // or bunyan, or any other logger that implements the same interface }); // track an event with optional properties mixpanel.track("my event", { distinct_id: "some unique client id", as: "many", properties: "as", you: "want", }); mixpanel.track("played_game"); // set an IP address to get automatic geolocation info mixpanel.track("my event", { ip: "127.0.0.1" }); // track an event with a specific timestamp (up to 5 days old; // use mixpanel.import() for older events) mixpanel.track("timed event", { time: new Date() }); // create or update a user in Mixpanel Engage mixpanel.people.set("billybob", { $first_name: "Billy", $last_name: "Bob", $created: new Date("jan 1 2013").toISOString(), plan: "premium", games_played: 1, points: 0, }); // create or update a user in Mixpanel Engage without altering $last_seen // - pass option $ignore_time: true to prevent the $last_seen property from being updated mixpanel.people.set( "billybob", { plan: "premium", games_played: 1, }, { $ignore_time: true, }, ); // set a user profile's IP address to get automatic geolocation info mixpanel.people.set( "billybob", { plan: "premium", games_played: 1, }, { $ip: "127.0.0.1", }, ); // set a user profile's latitude and longitude to get automatic geolocation info mixpanel.people.set( "billybob", { plan: "premium", games_played: 1, }, { $latitude: 40.7127753, $longitude: -74.0059728, }, ); // set a single property on a user mixpanel.people.set("billybob", "plan", "free"); // set a single property on a user, don't override mixpanel.people.set_once( "billybob", "first_game_play", new Date("jan 1 2013").toISOString(), ); // increment a numeric property mixpanel.people.increment("billybob", "games_played"); // increment a numeric property by a different amount mixpanel.people.increment("billybob", "points", 15); // increment multiple properties mixpanel.people.increment("billybob", { points: 10, games_played: 1 }); // append value to a list mixpanel.people.append("billybob", "awards", "Great Player"); // append multiple values to a list mixpanel.people.append("billybob", { awards: "Great Player", levels_finished: "Level 4", }); // merge value to a list (ignoring duplicates) mixpanel.people.union("billybob", { browsers: "ie" }); // merge multiple values to a list (ignoring duplicates) mixpanel.people.union("billybob", { browsers: ["ie", "chrome"] }); // record a transaction for revenue analytics mixpanel.people.track_charge("billybob", 39.99); // clear a users transaction history mixpanel.people.clear_charges("billybob"); // delete a user mixpanel.people.delete_user("billybob"); // delete a user in Mixpanel Engage without altering $last_seen or resolving aliases // - pass option $ignore_time: true to prevent the $last_seen property from being updated // (useful if you subsequently re-import data for the same distinct ID) mixpanel.people.delete_user("billybob", { $ignore_time: true, $ignore_alias: true, }); // Create an alias for an existing distinct id mixpanel.alias("distinct_id", "your_alias"); // all functions that send data to mixpanel take an optional // callback as the last argument mixpanel.track("test", function (err) { if (err) throw err; }); // track multiple events at once mixpanel.track_batch([ { event: "recent event", properties: { time: new Date(), distinct_id: "billybob", gender: "male", }, }, { event: "another recent event", properties: { distinct_id: "billybob", color: "red", }, }, ]); // ============================================================================ // Service Account Authentication (RECOMMENDED - Preferred Method) // ============================================================================ // Service accounts provide enhanced security for server-to-server integrations. // This is the PREFERRED authentication method. API secrets are deprecated. // Learn more: https://developer.mixpanel.com/reference/service-accounts-api const credentials = new ServiceAccountCredentials( "YOUR_SERVICE_ACCOUNT_USERNAME", "YOUR_SERVICE_ACCOUNT_SECRET", "YOUR_PROJECT_ID", ); const mixpanel_with_sa = Mixpanel.init("YOUR_TOKEN", { credentials }); // Import old events (uses service account auth) mixpanel_with_sa.import("old event", new Date(2012, 4, 20, 12, 34, 56), { distinct_id: "billybob", gender: "male", }); // Regular tracking (uses token in payload, no auth header needed) mixpanel_with_sa.track("test event", { distinct_id: "billybob", plan: "premium", }); // Service accounts can also be used with feature flags const mixpanel_flags = Mixpanel.init("YOUR_TOKEN", { credentials, local_flags_config: { // ... config }, }); // ============================================================================ // DEPRECATED: API Secret Authentication (Legacy - Not Recommended) // ============================================================================ // ⚠️ WARNING: API secrets are DEPRECATED and will be removed in a future version. // Please migrate to Service Account credentials above for enhanced security. var mixpanel_importer = Mixpanel.init("valid mixpanel token", { secret: "valid api secret for project", // DEPRECATED - use ServiceAccountCredentials instead }); // needs to be in the system once for it to show up in the interface mixpanel_importer.track("old event", { gender: "" }); mixpanel_importer.import("old event", new Date(2012, 4, 20, 12, 34, 56), { distinct_id: "billybob", gender: "male", }); // import multiple events at once mixpanel_importer.import_batch([ { event: "old event", properties: { time: new Date(2012, 4, 20, 12, 34, 56), distinct_id: "billybob", gender: "male", }, }, { event: "another old event", properties: { time: new Date(2012, 4, 21, 11, 33, 55), distinct_id: "billybob", color: "red", }, }, ]);

Service Account Authentication

Documentation: https://developer.mixpanel.com/reference/service-accounts-api

When to Use Service Accounts

Service account credentials are required for:

  • Importing historical events - Events older than 5 days via /import endpoint
  • Server-side feature flags - Evaluating feature flags with authentication

Service accounts are NOT needed for:

  • Regular event tracking - track() uses project token only
  • People analytics - people.set(), people.increment(), etc.
  • Group analytics - groups.set(), etc.

Migrating from API Secrets (Deprecated)

If you're currently using API secrets (deprecated), here's how to upgrade:

Before (deprecated):

// Old method - still works but deprecated var mixpanel = Mixpanel.init("TOKEN", { secret: "your-api-secret", }); mixpanel.import("event", new Date(2020, 1, 1), { distinct_id: "user123", });

After (recommended):

// New method - enhanced security with service accounts const { ServiceAccountCredentials } = Mixpanel; const credentials = new ServiceAccountCredentials( "service-account-username", // From Mixpanel project settings "service-account-secret", // From Mixpanel project settings "project-id", // Your Mixpanel project ID ); var mixpanel = Mixpanel.init("TOKEN", { credentials }); mixpanel.import("event", new Date(2020, 1, 1), { distinct_id: "user123", });

Key differences:

  • Service accounts use username/secret pairs instead of a single shared secret
  • Project ID is explicitly specified for better security
  • Each service account can have specific permissions
  • Easier to rotate credentials without affecting other integrations
  • Learn more: https://developer.mixpanel.com/reference/service-accounts-api

FAQ

Where is mixpanel.identify()?

mixpanel-node is a server-side library, optimized for stateless shared usage; e.g., in a web application, the same mixpanel instance is used across requests for all users. Rather than setting a distinct_id through identify() calls like Mixpanel client-side libraries (where a single Mixpanel instance is tied to a single user), this library requires you to pass the distinct_id with every tracking call. See https://github.com/mixpanel/mixpanel-node/issues/13.

How do I get or set superproperties?

See the previous answer: the library does not maintain user state internally and so has no concept of superproperties for individual users. If you wish to preserve properties for users between requests, you will need to load these properties from a source specific to your app (e.g., your session store or database) and pass them explicitly with each tracking call.

Tests

# in the mixpanel directory
npm install
npm test

Alternative Clients and Related Tools

  • Mixpanel-CLI - CLI for Mixpanel API (currently only supports tracking functions)
  • Mixpanel Data Export - Supports various query and data-management APIs; runs in both Node.js and browser
  • Mixpanel Data Export (strawbrary) - Fork of previous library, optimized for Node.js with support for streaming large raw exports

Attribution/Credits

Heavily inspired by the original js library copyright Mixpanel, Inc. (http://mixpanel.com/)

Copyright (c) 2014-21 Mixpanel Original Library Copyright (c) 2012-14 Carl Sverre

Contributions from:

  • Andres Gottlieb
  • Ken Perkins
  • Nathan Rajlich
  • Thomas Watson Steen
  • Gabor Ratky
  • wwlinx
  • PierrickP
  • lukapril
  • sandinmyjoints
  • Jyrki Laurila
  • Zeevl
  • Tobias Baunbæk
  • Eduardo Sorribas
  • Nick Chang
  • Michael G
  • Tejas Manohar
  • Eelke Boezeman
  • Jim Thomas
  • Frank Chiang
  • Morgan Croney
  • Cole Furfaro-Strode
  • Jonas Hermsmeier
  • Marko Klopets
  • Cameron Diver
  • veerabio
  • Will Neild
  • Elijah Insua
  • Arsal Imam
  • Aleksei Iatsiuk
  • Vincent Giersch

License

Released under the MIT license. See file called LICENSE for more details.

Dependencies Comparison

amplitude

Dependencies

axios^0.26.0

Dev Dependencies

nyc^15.1.0
chai^4.3.6
glob^7.2.0
nock^13.2.4
husky^7.0.4
mocha^9.2.0
sinon^13.0.1
eslint^8.9.0
lodash^4.17.21
codecov^3.8.3
ts-node^10.5.0
prettier^1.19.1
sinon-chai^3.7.0
typescript^4.5.5
@types/chai^4.3.0
@types/node^17.0.18
lint-staged^12.3.4
@types/mocha^9.1.0
@types/sinon^10.0.11
@types/eslint^8.4.1
@types/sinon-chai^3.2.8
eslint-config-prettier^8.3.0
eslint-plugin-prettier^4.0.0
@typescript-eslint/parser^5.12.0
@typescript-eslint/eslint-plugin^5.12.0

Peer Dependencies

mixpanel

Dependencies

json-logic-js2.0.5
https-proxy-agent7.0.6

Dev Dependencies

nock^14.0.10
proxyquire^2.1.3

Peer Dependencies

StarsIssuesVersionUpdatedⓘLast publish dateCreatedⓘPackage creation dateSizeⓘMinified + Gzipped size
A
amplitude
7136.0.04 years ago11 years agoinstall size 7.2 KB
M
mixpanel
488790.23.0a month ago15 years agoinstall size 13.3 KB

Who's Using These Packages

amplitude

i18n-ally
i18n-ally

🌍 All in one i18n extension for VS Code

amplitudejs
amplitudejs

AmplitudeJS: Open Source HTML5 Web Audio Library. Design your web audio player, the way you want. No dependencies required.

leek-fund
leek-fund

:chart_with_upwards_trend: 韭菜盒子插件,兼容 VS Code 生态编辑器。在你用 AI 专注于写代码的同时,它在后台实时且隐蔽地追踪着市场,绝不打断你的任何工作流。

frontend-fundamentals
frontend-fundamentals

Essential principles for frontend development

mobile-app
mobile-app

See your city's air pollution measured in daily cigarettes. iOS/Android.

mixpanel

qrbtf
qrbtf

AI & parametric QR code generator. AI & 参数化二维码生成器。https://qrbtf.com

flyde
flyde

Open-source Visual programming for backend logic that integrates with existing codebases. Flyde bridges the gap between technical and non-technical team members. Product managers, designers, and backend developers can collaborate on the same visual flows.

mixpanel-js
mixpanel-js

Official Mixpanel JavaScript Client Library

vscode-plugin
vscode-plugin

Kite Autocomplete Plugin for Visual Studio Code

devtools-remote
devtools-remote

Debug your browser tabs remotely via Chrome DevTools