Google Analytics Integration

Google Analytics is the most popular analytics library on the web because it’s free and has a wide range of features. We recommend dropping it into all your web projects.

We support classic and universal analytics for both client-side and the server-side, in addition to mobile app analytics for iOS and Android.

** Now that the Universal tracking method is out of beta we recommend everyone still using Classic tracking upgrades.These docs will focus on Universal features.

Getting Started

When you toggle on Google Analytics in Segment.io, this is what happens:

  • Our CDN is updated within 5-10 minutes. Then our snippet will start asynchronously loading Google Analytics javasctipt library onto your web page. This means you should remove Google’s snippet from your page.

  • Your Google Analytics real-time dashboard will start showing live concurrent visitors.

  • Any iOS and Android apps running our mobile libraries will start sending data to Google Analytics. New settings will take up to an hour to propogate to all of your existing users.Or if you just added the iOS or Android library to your app code, it’ll be instantaneous!

  • Google Analytics will start automatically collecting data on your site or mobile app. It takes several hours for Google to process this data and add it to your reports, but you should still see events showing up in their real-time events dashboard.

Google Analytics is supported on client-side, server-side, and mobile.

Pageviews

When you call .page(), we send a pageview to Google Analytics. Pageviews can be send from the browser or through any of our server-side libraries.

Virtual Pageviews

Virtual pageviews are when you send a pageview to Google Analytics when the page URL didn’t actually change. You can do this through Segment.io by simply calling .page() with optional page properties, like this:

analytics.page({
  title: 'Signup Modal',
  url: 'https://segment.io/#signup',
  path: '/#signup',
  referrer: 'https://segment.io/'
});

For more information about .page() check out the page method docs.

Events

We’ll create a Google Analytics custom event whenever you make a .track() call.

Events can be sent from the browser, your server, or our mobile SDKs.

Here’s a basic example:

These event attributes are sent to Google Analytics:

Event Category All
Event Action Logged In

And another example, this time with all Google Analytics event parameters:

That call will create a Google Analytics custom event with these attributes:

Event Category All
Event Action Logged In
Event Label Premium
Event Value 50

For Event Value you can name the event property value or revenue. Calling it revenue is best if the event made you money. That way we can also pass the revenue data to other integrations you have enabled.

Non-interaction Events

To create an event with the noninteraction flag just pass us an event property labeled noninteraction with the value of 1.

Here’s an example:

E-Commerce

Segment.io supports Google Analytics ecommerce tracking natively in client-side javascript. All you have to do is adhere to our ecommerce tracking API and we’ll make the necessary calls to Google Analytics in the background.

For Google Analytics ecommerce to work you must send these 2 ecommerce events through Segment.io:

  1. Added Product
  2. Completed Order

All of our ecommerce events are recommended, but not required.

The most important thing to remember in Google’s Universal Analytics is to enable ecommerce tracking for the view you want to track transactions to. This can be done inside of Google Analytics by clicking:

Admin > View Settings > Ecommerce Settings switch to ON

Without this step transactions will not show up in your reports.

Identifying Visitors

It is against Google’s terms of service to pass Personally Identifiable Information (PII) to your Google Anlaytics reporting interface. For that reason Segment.io will never pass anything from an .identify() call to Google unless you specifically tell us to.

User ID

Google Analytics Universal tracking method allows you to set a user ID for your identified visitors. Read more here.

If you want to pass the id from an .identify() call to Google - enable Send User-ID to GA in your Advanced Google Analytics settings on the Segment.io integrations page.

Here’s an example:

analytics.identify('12345', {
  email: 'friends@segment.io',
  name: 'Jake Peterson'
});

In this example we will set the User-ID to 12345 for Google Analytics, but we won’t share the email or name traits with Google.

If you are passing an email, username, name or other PII as the id in .identify() do not use this feature. That is against the Google Analytics terms of service and your account could be suspended.


Classic or Universal?

There are two ways to send data to Google Analytics.

  • Classic Analytics - requesting a GIF pixel from the GA servers.
  • Universal Analytics - a new REST API for Google Analytics that became the default collection method in March 2013.

The Universal tracking method is Google’s preferred method and all new properties will be Universal properties by default.

Am I Using Classic or Universal?

  1. Go to your Google Analytics Account.
  2. Navigate to Admin > Tracking Info
  3. If your javascript snippet contains ga.js then you’re using Classic Analytics. If your javascript snippet contains analytics.js, then you’re using Universal Analytics.

We recommend upgrading to Universal if you are currently using the Classic tracking method. Segment.io supports both, but Google is fading out the Classic tracking method.


Mobile Apps

Segment.io supports Google Analytics mobile app analytics via our iOS and Android libraries. For getting started with our mobile libraries, check out the iOS and Android technical docs.

You’ll need to create a new Google Analytics property for your mobile app. You can’t mix website and mobile apps within the same GA property. You can however mix Android and iOS implementations of the same app, or many different builds of the same app inside the same property.

Here are Google’s Best Practices for Mobile App Analytics:

  • Track different apps in seperate properties
  • Track different platforms of an app in the same property
  • Track app editions based on feature similarities
  • Track different app versions in the same property

Screen

This method is used to record screen views, similar to pageviews in the browser version of GA. Here’s an example screen call on iOS:

[[Analytics sharedAnalytics] screen:@"Signup"];

For more check out our screen method docs.

Add the Mobile Tracking Id Field

The first thing you’ll want to do is to add the Mobile Tracking Id to your Google Analytics settings inside Segment.io.

When Will I See Data?

If you already have an app deployed with the Segment.io library, and you just turned on Google Analytics mobile, it will take up to an hour for all your mobile users to refresh their Segment.io settings cache, and learn about the new service that you want to send to.

After the settings cache refreshes, our library will automatically start sending data to Google Analytics.

Android Permissions

You’ll need to make sure you added these permissions to your AndroidManifest.xml:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Calling Google Analytics Directly

Since our SDKs bundle the Google Analytics SDK, you can access the Google Analytics Tracker object directly. Here’s an Android example:

GoogleAnalytics ga = GoogleAnalytics.getInstance(this);
Tracker tracker = ga.getDefaultTracker();
// perform custom actions, such as setting custom dimensions
tracker.setCustomDimension(1, "myValue");
tracker.sendView();

This allows you to perform custom actions with Google Analytics, such as e-commerce transaction tracking.


Server Side

When you track an event or pageview with one of our server-side libraries or HTTP API we will send it along to the Google Analytics REST API.

Automatic Non-Interaction Events

We mark all server-side events as non-interaction events. This prevents server-side events from affecting your bounce rate measurement.

Combining Server-side and Client-side Events

Google Analytics uses cookies to keep track of visitors and their sessions while visiting your website. The cookie data is stored in the visitor’s browser, and is sent along to Google Analytics every time a new pageview or event occurs. This allows GA to show a single unique visitor between multiple page reloads.

Your servers also have access to this cookie, so they can re-use it when you send server-side events to Segment.io. If you don’t use the existing cookie Segment.io has to create a new one to make the server-side request to GA. When we create a new cookie the client-side and server-side events from the same user will look like two distinct visitors in Google Analytics.

If you want to use server-side Google Analytics, there are three options with Segment.io:

  1. Pass your Google Analytics cookies to Segment.io (preferred).
  2. Use two Google Analytics profiles: one for client-side data and one for server-side data.
  3. Ignore the additional visitors generated by not passing the cookie.

Passing Cookies from Universal Analytics

Universal Analytics (analytics.js) uses the clientId to keep track of unique visitors.

A Google Analytics Universal cookie will look like this:

_ga=GA1.2.1033501218.1368477899;

The clientId is this part: 1033501218.1368477899

You can double check that it’s your clientId by running this script in your javascript console:

ga(function (tracker) {
    var clientId = tracker.get('clientId');
    console.log('My GA universal client ID is: ' + clientId);
});

If you want our server-side integration to use your user’s clientId, pass it to us in the context['Google Analytics'].clientId object.

Here’s a Ruby example:

Analytics.track(
  user_id: '019mr8mf4r',
  event: 'Purchased a Bear',
  properties: {
    item     : 'Bear Repellent',
    quantity : 10,
    revenue  : '9.95'
  },
  context: {
    'Google Analytics' => {
        clientId: '1033501218.1368477899'
    }
  }
)

Passing Cookies from Classic Analytics

Classic Analytics (ga.js) uses the utmcc cookie to keep track of your visitor and session. If you want server-side Google Analytics events to be tied to real visitors, then you’ll want to pass the utmcc cookie in the context['Google Analytics'].utmcc object.

Here’s a Ruby example:

utma = request.cookies['__utma'] # grab the __utma cookie value
utmz = request.cookies['__utmz'] # same for the __utmz cookie
context = {}

# Only send along the cookie if it actually exists
unless utma.nil? and utmz.nil?
  context['Google Analytics'] = { utmcc: "__utma=#\{utma\}; __utmz=#\{utmz\}" }
end

Analytics.track(
  user_id: "019mr8mf4r",
  event: "Purchased an Item",
  properties: {
    item: "Starcraft T-Shirt",
    quantity: 50,
    revenue: "19.95"
  },
  context: context
)

User Agent

By default, we won’t set the user-agent header. If you have your user’s user-agent server-side, you can send it to us using the context object. The context object is an optional argument supported by all of our server-side libraries.

Here’s a Ruby example:

Analytics.track(
  user_id: '019mr8mf4r',
  event: 'Loaded a Page',
  properties: {
    url: 'http://initech.com/pricing',
    referrer: 'http://techcrunch.com/initech'
  },
  context: {
    userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.57 Safari/537.17'
  }
)

Visitor Geo-Location

Google Analytics uses the IP address of the HTTP request to determine the location of the visitor. This happens automatically for client-side and mobile tracking, but takes a little more work for server-side calls.

For geo-location to work from a server-side call you’ll need to include the visitor’s ip in your .track() call.

Here’s a Ruby example:

Analytics.track(
    user_id: '019mr8mf4r', 
    event: 'Purchased Item', 
    properties: { revenue: 39.95 }
    context: { ip: '11.1.11.11' })

Advanced

We support all of the following Google Analytics features:

Anonymize IP Address

Just check the box in your advanced Google Analytics settings inside of Segment.io.

Custom Dimensions

Google Analytics Custom Dimensions through Segment.io is currently in Beta. If you’re interested in using this feature email us: friends@segment.io.

Doubleclick Remarketing

Google’s Doubleclick remarketing is used to tag visitors for remarketing campaigns. It is also used to identify demographic and interest data on visitors that is displayed in Demographic & Interest reports inside of Google Analytics.

Turn this feature on by checking the box in your Google Analytics settings on the Segment.io integrations page. Doubleclick works with Universal and Classic tracking methods.

Since Doubleclick is loaded through Segment.io Google Analytics will not be able to validate that the code is present on the page. Just click Skip validation and your data will start showing up within a few hours.

Across Sub-domains

This works automatically if you’re using the Universal tracking method. To track across sub-domains we recommend upgrading to universal if you haven’t already.

If you need to set a specific domain name keep reading :)

Override Domain Name

The Google Analytics Override Domain Name setting allows you to specify the domain that the _ga cookie will be set on. By default the cookie is placed on the top level domain: domain.com.

We default the Override Domain Name setting to the special value none, which will allow you to track across multiple sub-domains and localhost. You can find this setting on your Segment.io integrations page under Google Analytics Advanced settings.

If you don’t want to allow localhost tracking, but want to track between multiple sub-domains, then you need to set the value to the top domain, omitting . or www. prefixes.

For example, if you are tracking users across these domains and don’t want to track localhost:

  • initech.com
  • swingline.initech.com
  • conclusions.initech.com

You’ll want to set the Override Domain Name to the highest top level domain, which in this case is: initech.com

If you only want the cookie to persist on a single sub-domain, enter that sub-domain in the Override Domain Name field, like this: swingline.initech.com. In this case visitors to conclusions.initech.com or initech.com will not be tracked.

Again - Remember to keep none while you’re testing on localhost.

Ignored Referrers

For Universal Properties:

This is only necessary for GA properties using the Classic tracking method. Universal properties can edit their ignored referrers in the Google Analytics admin interface.

For Classic Properties:

Sometimes you want Google Analytics to ignore certain referral domains, for example to prevent your sub-domains from showing up as referrers in your analytics. Add any domains you want to ignore to the Ignored Referrers list in your Google Analytics settings inside of Segment.io, separated by line breaks.

Cross-Domain Tracking

Segment.io supports Google Analytics tracking across multiple top level domains, but it requires a bit of work from you.

When a visitor comes to your website, domain1.com, Google Analytics sets a first-party cookie that represents that user. That cookie looks like 182119591.1441315536, and is tied to domain1.com (making it a first party cookie).

When your visitor clicks a link to go another domain, let’s say domain2.com, you’ll need to tell the new site about the domain1.com cookie. This is done by rewriting your domain2.com links to include this domain1.com cookie, like so:

http://company2.com?_ga=1.182119591.1441315536.1362115890410

Luckily, Google Analytics providers an auto-linking plugin to make this easier. To access the ga methods while using Segment.io they must be inside an analytics.ready() function, like this:

analytics.ready(function () {
    ga('require', 'linker');
    ga('linker:autoLink', ['company2.com']);
});

To make things easy Segment.io enables allowLinker by default so all you need to do is run these two functions with any domains you want to track across to in the second call above.

You’ll want to carefully read the Google Analytics Domain Guide to get this setup.

Webmaster Tools

When you use Segment.io to load Google Analytics, our script loads the Google Analytics script. If you use Google Analytics as the verification option in Google Webmaster Tools, you’ll need to switch to the Meta tags verification option instead. This will require you to find the <meta name=google-site-verification" ..> tag in Webmaster Tools and place it in your master HTML template.

Cannonical Urls

We take care of tracking the canonical URL to Google Analytics for you automatically. As long as there is a <meta rel="canonical"> tag on your page, we’ll make sure Google Analytics gets the right canonical URL from it.


Troubleshooting

Real-Time Reports

Google Analytics doesn’t process their data in real-time in most of their reports. The easiest way to see if the data is streaming in is to check the Real-Time reports inside Google Analytics.

Time Frame

Google Analytics’s default reporting time frame is a month ago to yesterday. You’ll need to adjust it from a month ago to today’s date to see today’s already processed events.

HTTPS

If your site uses https://, please go to your Google Analytics property settings page and change your Site URL to use the https:// protocol.

Bounce Rates

Using Segment.io won’t affect your bounce rates in Google Analytics.

If you see your bounce rates drop after installing Segment.io make sure you don’t have multiple copies of our snippet on your page. Also be sure you’re not calling .page() more than once when the page loads.

If you call .track() on page load make sure to set noninteraction to 1, more details here.

Open Source

If you’re using the open source version of analytics.js, you can set any of these settings in the initialize function. All but trackingId are optional. We’ll default to universal analytics.

Here’s an example (only the trackingId is required):

analytics.initialize({
    'Google Analytics' : {
        trackingId              : 'UA-xxxxxx-x',
        universalClient         : false,
        domain                  : 'example.com',
        ignoreReferrer          : 'example.com',
        enhancedLinkAttribution : true,
        siteSpeedSampleRate     : 5,
        anonymizeIp             : true
    }
});

If you ever have any questions, or see anywhere we can improve our documentation, just shoot us an email at friends@segment.io!