Collecting data with Trackers and Webhooks

  1. Home
  2. Docs
  3. Collecting data with Trackers and Webhooks
  4. Trackers – collecting data from your own applications
  5. Javascript Tracker
  6. General Parameters
  7. Getting the userID from the Snowplow Cookie

Getting the userID from the Snowplow Cookie

You can use the following function to extract the user ID from the ID cookie:

/* * Function to extract the Snowplow user ID from the first-party cookie set by the Snowplow JavaScript Tracker * * @param string cookieName (optional) The value used for "cookieName" in the tracker constructor argmap * (leave blank if you did not set a custom cookie name) * * @return string or bool The ID string if the cookie exists or false if the cookie has not been set yet */ function getSnowplowDuid(cookieName) { cookieName = cookieName || '_sp_'; var matcher = new RegExp(cookieName + 'id\\.[a-f0-9]+=([^;]+);?'); var match = document.cookie.match(matcher); if (match && match[1]) { return match[1].split('.')[0]; } else { return false; } }

If you set a custom cookieName field in the argmap, pass that name into the function; otherwise call the function without arguments. Note that if the function is called before the cookie exists (i.e. when the user is visiting the page for the first time and sp.js has not yet loaded) if will return false.