Find and track frontend bugs using Google Analytics

March 23, 2014

Read time 2 min

Find your Frontend bugs and stop guessing ROI for a bug fix.

This post describes how to use Google Analytics with requirejs to track errors in frontend.

Google Analytics events

GA events are grouped by Category, Action and Label. All JavaScript errors can be captured using window.onerror -handler.
As end result GA looks like this in case of a frontend bug:


Setting things up with Google Analytics

  • Create a GA account and two properties: one for testing purposes (handy also for integration tests) and one for production.
  • Configure your local web server to serve pages you are developing singe GA will not accept file protocol.
  • GA is always disabled for localhost. In order to test locally use IP address or some custom domain name. With Mac you can just use computer_name.local.

Basic setup

window._gaq = window._gaq || []
window._gaq.push(['_setAccount', (isProduction ? productionAccountId : testAccountId)])

Tracking JavaScript errors

window.onerror(function(e) {
  var category = 'JavaScript error'
  var action = e.message
  var label = e.filename + ':' + e.lineno
  _gaq.push(['_trackEvent', category, action, label]);

Tracking ajax errors

function ajaxErrorHandler(e) {
  var category = 'Ajax error'
  var action = e.status + ' - ' + e.statusText
  var label = e.responseText
  _gaq.push(['_trackEvent', category, action, label]);

$.get('', $.noop).fail(ajaxErrorHandler)


In order to make debugging easier Google provides instead of to log to console all tracking events.

Here’s the code for requiring proper GA bootstrap file:

function getGaUrl(isDebug) {
  var isHttps = 'https:' === document.location.protocol
  return (isHttps ? 'https://ssl' : 'http://www') + '' + 
    (isDebug ? 'u/ga_debug.js' : 'ga.js')

With this configuration GA will show following information in console for different tracking events.


Try out a Live Demo.

Full example can be found in Github

Sign up for our newsletter

Get the latest from us in tech, business, design – and why not life.