Linus Unnebäck
Linus Unnebäck

Reputation: 24291

Migrate Google Analytics storage from cookies to local storage

Before we knew about the different storage options for Google Analytics (analytics.js) we launched our site and used the default, cookie-based, tracking. We now want to switch to storing the client id using localStorage, so that we don't have to send the cookies to the server for each request.

Is it possible to migrate users who have the cookie set, so that not every session will show up as a new brand new user?

Upvotes: 1

Views: 1391

Answers (1)

Linus Unnebäck
Linus Unnebäck

Reputation: 24291

It's certainly possible, the trick is to let the Google Analytics script extract the client id from the cookie for you when you can't find an id stored in local storage.

/* Google Analytics initialization code */
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga')

/* Fallback to cookies if the browser doesn't support localStorage */
if (!window.localStorage) {
  ga('create', 'UA-XXXXX-Y', 'auto')
}

/* If we are already using localStorage, continue with that */
else if (localStorage.getItem('gaClientId')) {
  ga('create', 'UA-XXXXX-Y', { storage: 'none', clientId: localStorage.getItem('gaClientId') })
}

/* Migrate users from cookies to localStorage */
else if (document.cookies.indexOf('_ga') !== -1) {
  ga('create', 'UA-XXXXX-Y', { cookieExpires: 1 })
  ga(function (tracker) { localStorage.setItem('gaClientId', tracker.get('clientId')) })
}

/* Setup a fresh user */
else {
  ga('create', 'UA-XXXXX-Y', { storage: 'none' })
  ga(function (tracker) { localStorage.setItem('gaClientId', tracker.get('clientId')) })
}

ga('send', 'pageview')

After the previous cookie timeout (defaults to 2 years if not specified), it should be safe to remove the cookie-migration part. The script would then look something like this:

/* Google Analytics initialization code */
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga')

/* Fallback to cookies if the browser doesn't support localStorage */
if (!window.localStorage) {
  ga('create', 'UA-XXXXX-Y', 'auto')
}

/* Store Google Analytics client ID in localStorage */
else {
  ga('create', 'UA-XXXXX-Y', { storage: 'none', clientId: localStorage.getItem('gaClientId') })
  ga(function (tracker) { localStorage.setItem('gaClientId', tracker.get('clientId')) })
}

ga('send', 'pageview')

Upvotes: 2

Related Questions