Google Analytics and Vaadin

Whether you think about it from the start or not, every web application needs some kind of user monitoring. Questions such as “Do users have trouble registering?”, “Why don’t they buy product x?” need clear answers in order to move your site forward. A typical Vaadin application can not be used with some of the most popular web site analytics tools such as Google Analytics. A Vaadin application runs on one page, so it’s impossible to track users in the “old-fashioned” way.

There is however a user friendly Vaadin component that allows you to track user actions. It’s called GoogleAnalyticsTracker and this post goes into an important issue you might face when you try it out.

As you might have noticed, this week is Vaadin week on Streamhead.

If you follow the instructions that come with the add on, you already know everything you need to know. Instantiate the tracker and call the measurement function whenever you want to log an action.

That’s all good and well, but it won’t work locally. It took me a while (too long) to figure out, but it turns out the Google Analytics JavaScript code verifies the domain you give the tracker with the actual domain the site runs on.

On localhost, this doesn’t work.

You can enter “none” as a host though, this will allow you to see the analytics request and verify everything is working as expected. So you might want to write a small helper function to set the correct domain. Something like this:

new GoogleAnalyticsTracker("UA-XXXXXXXX-1", getDomain());
...
private String getDomain() {
        final URL url = getURL();
        if(url == null)
                return "none";
        final String host = url.getHost();
        if(host == null)
                return "none";
        return host.contains("mydomain.com") ? "mydomain.com" : "none";
}