Giter VIP home page Giter VIP logo

amplitude's Introduction

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.

Contributors

amplitude's People

Contributors

crookedneighbor avatar cymruu avatar dependabot[bot] avatar geoffdutton avatar greenkeeper[bot] avatar greenkeeperio-bot avatar mattpardee avatar michaelvol avatar mjk avatar modosc avatar snyk-bot avatar zatteo avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

amplitude's Issues

Action required: Greenkeeper could not be activated 🚨

🚨 You need to enable Continuous Integration on Greenkeeper branches of this repository. 🚨

To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because it uses your CI build statuses to figure out when to notify you about breaking changes.

Since we didn’t receive a CI status on the greenkeeper/initial branch, it’s possible that you don’t have CI set up yet.
We recommend using:

If you have already set up a CI for this repository, you might need to check how it’s configured. Make sure it is set to run on all new branches. If you don’t want it to run on absolutely every branch, you can whitelist branches starting with greenkeeper/.

Once you have installed and configured CI on this repository correctly, you’ll need to re-trigger Greenkeeper’s initial pull request. To do this, please click the 'fix repo' button on account.greenkeeper.io.

Retry for 429

I see that the library is using axios, does it support axios retry library?

error TS2304: Cannot find name 'ProgressEvent'

Hi,

lately, I'm getting this error while building (fail)

node_modules/amplitude/node_modules/axios/index.d.ts(62,38): error TS2304: Cannot find name 'ProgressEvent'.
node_modules/amplitude/node_modules/axios/index.d.ts(63,40): error TS2304: Cannot find name 'ProgressEvent'.

License

Hi team,

How is this package licensed? Would it be possible to add a LICENSE file?

Thank you for maintaining this project!

An in-range update of superagent is breaking the build 🚨

The dependency superagent was updated from 5.2.1 to 5.2.2.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

superagent is a direct dependency of this project, and it is very likely causing it to break. If other packages depend on yours, this update is probably also breaking those in turn.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).
  • Travis CI - Branch: The build errored.

Release Notes for v5.2.2

v5.2.1...v5.2.2

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Error: Client network socket disconnected before secure TLS connection was established

Getting this error when trying to track an event.

Here is the full error:

Unhandled Promise Rejection
{
"errorType": "Runtime.UnhandledPromiseRejection",
"errorMessage": "Error: Client network socket disconnected before secure TLS connection was established",
"reason": {
"errorType": "Error",
"errorMessage": "Client network socket disconnected before secure TLS connection was established",
"code": "ECONNRESET",
"path": null,
"host": "api.amplitude.com",
"port": 443,
"stack": [
"Error: Client network socket disconnected before secure TLS connection was established",
" at connResetException (internal/errors.js:570:14)",
" at TLSSocket.onConnectEnd (_tls_wrap.js:1361:19)",
" at Object.onceWrapper (events.js:299:28)",
" at TLSSocket.emit (events.js:215:7)",
" at endReadableNT (_stream_readable.js:1183:12)",
" at processTicksAndRejections (internal/process/task_queues.js:80:21)"
]
},
"promise": {},
"stack": [
"Runtime.UnhandledPromiseRejection: Error: Client network socket disconnected before secure TLS connection was established",
" at process. (/var/runtime/index.js:35:15)",
" at process.emit (events.js:210:5)",
" at processPromiseRejections (internal/process/promises.js:201:33)",
" at processTicksAndRejections (internal/process/task_queues.js:94:32)"
]
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.