NodeJS (20.11)


This documentation shows how to use Countly NodeJS SDK to track your nodejs running device or server, like tracking your API.

Before starting, for those who have examined our mobile SDKs - we can tell that events or tags that are used in mobile SDKs are quite similar to those we use in Javascript code. For example, it's possible to modify custom property values of user details, with modification commands like inc, mul, max, or min. Likewise, any event can be sent with segmentation easily.

What is an APP KEY?

You'll see APP_KEY definition above. This key is generated automatically when you create a website for tracking on Countly dashboard. Note that APP KEY is different from API KEY, which is used to send data via API calls.

To retrieve your APP_KEY, go to Management -> Applications and select your app, and you will see App Key field

Setting up

To add the SDK to your project, you would use a command similar to these:

npm yarn
npm install countly-sdk-nodejs

Example setup would look like this:

var Countly = require('countly-sdk-nodejs');

    app_key: "{YOUR-API-KEY}",
    url: "https://API_HOST/",
    debug: true


Which API HOST name should I use to send data to?

If you are using Countly Enterprise trial servers use, or Basically the domain you are accessing your trial dashboard from.

If you use Countly Lite and Countly Enterprise, use your own domain name or IP address like or https://IP (if SSL is setup).

Now you can make event calls like:

    "key": "in_app_purchase",
    "count": 3,
    "sum": 2.97,
    "dur": 1000,
    "segmentation": {
        "app_version": "1.0",
        "country": "Germany"

Setup properties

Here are the properties you can setup on Countly initialization

  • app_key - mandatory, app key for your app created in Countly
  • device_id - to identify a visitor, will be auto generated if not provided
  • url - your Countly server url (default: ""), you must use your own server URL here
  • app_version - (optional) the version of your app or website
  • country_code - (optional) country code for your visitor
  • city - (optional) name of the city of your visitor
  • ip_address - (optional) ip address of your visitor
  • debug - output debug info into console (default: false)
  • interval - set an interval how often to check if there is any data to report and report it (default: 500 ms)
  • fail_timeout - set time in seconds to wait after failed connection to server (default: 60 seconds)
  • session_update - how often in seconds should session be extended (default: 60 seconds)
  • max_events - maximum amount of events to send in one batch (default: 10)
  • force_post - force using post method for all requests (default: false)
  • storage_path - where SDK would store data, including id, queues, etc (default: "../data/")
  • require_consent - pass true if you are implementing GDPR compatible consent management. It would prevent running any functionality without proper consent (default: false)
  • remote_config - Enable automatic remote config fetching, provide callback function to be notified when fetching done (default: false)
  • http_options - function to get http options by reference and overwrite them, before running each request
  • max_logs - maximum amount of breadcrumbs to store for crash logs (default: 100)
  • metrics - provide for this user/device, or else will try to collect what's possible

Setting up properties in Countly NodeJS SDK is as follows (if you have your own server, use it instead of

    url: "",
    app_version: "1.2",
    country_code: "LV",
    city: "Riga",
    ip_address: "",
    http_options: function(options){
        options.headers["user-agent"] = "Test";
        _os: "Ubuntu",
        _os_version: "16.04",
        _device: "aws-server"

Helper methods

Helper methods created to allow you easily track most common actions

Track Views

This method allows you to track different parts of your application, called views. You can track how much time is spent on each part of the application.


And optionally, as the third parameter, you can provide view segments (key/value pairs) to track together with the view. There is a list of reserved segment keys that should not be used:

  • start
  • visit
  • bounce
  • end
  • name
  • domain
  • view
  • segment
  • platform
//Provide view segments
Countly.track_view("viewname", {theme:"red", mode:"fullscreen"});

Report conversion

When using Countly attribution analytics, you can also report conversion to Countly server, like for example when visitor purchased something or registered.

Note: that conversion for each user may be reported only once, all other conversions will be ignored for this same user

//or provide campaign id yourself

Make raw request

Sometimes if you are switching between users a lot, or changing some other data, which is hard to handle over multiple processes, etc. You can simply make a raw request with all possible SDK parameters described in API reference



Adding an event

An event is a way to track any custom actions or other data you want to track from your website. You can also provide segments to be able to view breakdown of action by provided segment values.

An event consists of Javascript object with keys: * key - the name of the event (mandatory) * count - number of events (default: 1) * sum - sum to report with event (optional) * dur - duration to report with event (optional) * segmentation - an object with key/value pairs to report with event as segments

Here is an example of adding an event with all possible properties:

  "key": "click",
  "count": 1,
  "sum": 1.5,
  "dur": 30,
  "segmentation": {
    "key1": "value1",
    "key2": "value2"

Data passed should be in UTF-8

All data passed to Countly instance via SDK or API should be in UTF-8.

Timed Events

You can report time or duration with every event by providing dur property of the events object. But if you want, you can also let Web SDK to track duration of some specific event for you, you can use start_event and end_event methods.

Firstly you can start tracking event time by providing name of the event (which later on will be used as key for event object)


Countly will internally mark the start of event and will wait until you end event with end_event method, setting up dur property based on how much time has passed since start_event for same event name was called.

//end event

//or end event with additional data
  "key": "timedEvent",
  "count": 1,
  "sum": 1.5,
  "segmentation": {
    "key1": "value1",
    "key2": "value2"

User Profiles and Custom data

User details

If you have any details about the user/visitor, you can provide Countly with that information. This will allow you track each and specific user on "User Profiles" tab, which is available with Countly Enterprise.

The list of possible parameters you can pass is:

    "name": "Arturs Sosins",
    "username": "ar2rsawseen",
    "email": "",
    "organization": "Countly",
    "phone": "+37112345678",
    //Web URL pointing to user picture
    "picture": "", 
    "gender": "M",
    "byear": 1987, //birth year

Modifying custom data

Additionally you can do different manipulations on custom data values, like increment current value on server or store array of values under same property.

Below is the list of available methods:

Countly.userData.set(key, value) //set custom property
Countly.userData.set_once(key, value) //set custom property only if property does not exist
Countly.userData.increment(key) //increment value in key by one
Countly.userData.increment_by(key, value) //increment value in key by provided value
Countly.userData.multiply(key, value) //multiply value in key by provided value
Countly.userData.max(key, value) //save max value between current and provided
Countly.userData.min(key, value) //save min value between current and provided
Countly.userData.push(key, value) //add value to key as array element
Countly.userData.push_unique(key, value) //add value to key as array element, but only store unique values in array
Countly.userData.pull(key, value) //remove value from array under property with key as name //send userData to server

Tracking Javascript errors

Countly also provides a way to track NodeJS errors on your server.

To automatically capture and report Javascript errors on your server, call the following function:


You can additionally add more segments or properties/values to track with error reports, by providing an object with key/values to add to error reports.

  "facebook_sdk": "2.3",
  "jquery": "1.8"

Apart from reporting unhandled errors automatically, you can also report handled exceptions to server too, so you can figure out how and even if you need to handle them later on. And optionally you can again provide custom segments to be used in the report (or use the ones provided with track_error method as default ones)

Countly.log_error(error, segments);

  //do something here
  //report error to Countly

To better understand what happened prior to getting an error, you can leave out breadcrumbs through out the code, on different actions. This breadcrumb will be then combined in single log and reported to server too.

Countly.add_log("user clicked button a");

Other methods

Changing Device ID

In some cases you may want to change the ID of the user/device that you provided or Countly generated automatically, for example, when user was changed.


In some cases, you may also need to change user's device ID in a way, that server will merge data of both user IDs (existing and new ID you provided) on the server, e.g., when user used website without authenticating and have recorded some data, and then authenticated and you want to change ID to your internal id of this user, to keep tracking it across multiple devices.

This call will merge any data recorded for current ID and save it as user with new provided ID.

Countly.change_id("myNewId", true);

Tracking a session

Beginning a session

This method would allow you to control sessions manually. Use it only, if you don't call track_sessions method.

If noHeartBeat is true, then Countly SDK won't extend session automatically, and you would need to do that manually.


Extending a session

By default (if noHeartBeat was not provided in begin_session) Countly SDK will extend session itself, but if you chose not to, then you can extend is using this method and provide seconds since last call begin_session or session_duration call, whatever was the last one.


Ending a session

When visitor is leaving your app or website, you should end his session with this method, optionally providing amount of seconds since last begin session or session_duration calls, whatever was the last one.


Performance monitoring

You can report a trace using report_trace method. Contents of it depend on which trace you report.

Here is an example of how to report network trace:

//report network trace
    type: "network", //device or network
    name: "/some/endpoint", //use name to identify trace and group them by
    stz: 1234567890123, //start timestamp in miliseconds
    etz: 1234567890123, //end timestamp in miliseconds
    app_metrics: {
        response_time: 1000,
        response_code: 200,
        response_payload_size: 12345,
        request_payload_size: 5432

 And here is an example of device trace:

//user built in method to report app start time

//or report device trace manually
    type: "device", //device or network
    name: "My App", //use name to identify trace and group them by
    stz: 1234567890123, //start timestamp in miliseconds
    etz: 1234567890123, //end timestamp in miliseconds
    app_metrics: {
        duration: 1000,

Or you can report any custom traces to provide duration:

//or report device trace manually
    type: "device", //device or network
    name: "Some process we launched", //use name to identify trace and group them by
    stz: 1234567890123, //start timestamp in miliseconds
    etz: 1234567890123, //end timestamp in miliseconds
    app_metrics: {
        duration: 1000,

Report feedback

If there is any way you can get some user feedback, there is not a simple method to report collected data to Countly.

//user feedback
    contactMe: true,
    rating: 5,
    email: "",
    comment: "Very good"


Looking for help?