Created
February 23, 2018 00:34
-
-
Save oddnavy/ee070c742d8b7c31b16b17cf2fc226bb to your computer and use it in GitHub Desktop.
User Tracker - Roughly follows the Google Analytics tracker implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { pick } from 'lodash'; | |
import Cookies from 'js-cookie'; | |
import queryString from 'query-string'; | |
const utmParams = [ | |
'utm_source', | |
'utm_medium', | |
'utm_campaign', | |
'utm_term', | |
'utm_content', | |
]; | |
// Only set once when at start of session | |
if (!Cookies.get('userTracker')) { | |
const userTracker = {}; | |
// convert query string to object | |
const searchParams = queryString.parse(location.search); | |
// Only pull valid UTM params not all query params | |
const campaignParams = pick(searchParams, utmParams); | |
// Test for missing utm_source or utm_medium | |
const noSourceOrMedium = (!campaignParams.utm_source || !campaignParams.utm_medium); | |
// Test for organic search referral | |
const searchReferral = document.referrer.match(/https?:\/\/(.*)\.(google|bing|yahoo)\.([^/?]*)/); | |
// Sensible defaults for missing utm_source or utm_medium | |
if (noSourceOrMedium) { | |
if (searchParams.gclid) { | |
campaignParams.utm_source = 'google'; | |
campaignParams.utm_medium = 'cpc'; | |
} else if (searchReferral) { | |
campaignParams.utm_source = searchReferral[2]; | |
campaignParams.utm_medium = 'organic'; | |
} else if (document.referrer) { | |
campaignParams.utm_source = document.referrer; | |
campaignParams.utm_medium = 'referral'; | |
} | |
campaignParams.utm_source = 'direct'; | |
campaignParams.utm_medium = 'none'; | |
} | |
// Store as a property in case we want additional data in userTracker | |
userTracker.campaignParams = campaignParams; | |
// Store userTracker as cookie for duration of session | |
Cookies.set('userTracker', userTracker, { | |
secure: true, | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment