Tips & Tricks

Include User ID, Version and Session

TrackJS allows several places for you to specify additional information about your application and who’s using it. This information can provide valuable context when fixing errors.

Include userId

One of the most useful pieces of information is who’s using your application. You may specify the ID of the user in two different ways:

// If you know the user at load time
window._trackJs = {
  userId: "John Doe"
  // other configuration
}

// Or, if you don't know the user at page load
// You can specify it at any other time with
trackJs.configure({ userId: "John Doe"})

The value for userId can be any string - something meaningful to you. We provide full support for grouping, filtering and trending on which users are experiencing errors. This also lets you be proactive, and reach out to users who may have had trouble!

Include version and sessionId

Similar to specifying the user, we offer two other string based fields for additional context.

version is intended for storing your application version. This can be a semantic versioning string, or a git commit hash, or really anything else. In the near future we will be producing additional reporting in regards to errors by version.

sessionId is intended to help you correlate errors in our system with any other systems you may have. This can be any string value as well, and will be displayed on the error details screen.

window._trackJs = {
  version: "1.4.6",
  sessionId: "1acecc2b-395f-4aa8-b3a1-391c7336235d"
}

// Alternatively, these can also be configured after page load
trackJs.configure({
  version: "1.4.6",
  sessionId: "1acecc2b-395f-4aa8-b3a1-391c7336235d"
})

Use console.log in Production

Anything logged using console.log or console.info will be seen in your telemetry timeline. You can use your console just like a normal server side logging platform. If you’re worried that your users might see things, you can turn off console visibility in production with the following configuration:

window._trackJs = {
  token: "YOUR_TOKEN_HERE",
  console: {
    display: false // Hides console logs from the users/dev tools, but keeps them in your timeline
  }
}

You’ll still get great context from your console logs, but your users won’t be concerned by it!

Dealing with Script Error

If your page loads scripts from different domains, you might see a lot of Script Error messages. These unhelpful messages occur because the browser’s same-origin security policy is preventing the error information from one domain (hosting scripts) from leaking to another (your page). There are three ways to solve this:

Cross-Origin Resource Sharing

Modern browsers (latest Chrome and Firefox) will honor the CORS headers when chosing whether to expose error information between domains. The hosting server must have CORS Headers enabled. Then, when including the script tag, add the crossorigin attribute to the tag.

<script src="//hosted.com/path/to/script" crossorigin="anonymous"></script>

Check out this blog post for more information about CORS scripts.

Ignore Them

If nothing else works, you can hide these errors from the UI. You should note that these are real errors, TrackJS just doesn’t have the details for them. Make sure you really don’t care about these before hiding them.

On the Data page just check the “Script Error” quick link, and you won’t see them anymore!

Developing Locally

TrackJS helps you understand how end users encounter errors in your app–but you probably don’t need all our monitoring capabilities in local or development environments. Moreso, you probably want to explicitly disable TrackJS locally to prevent our obfuscation of console messages and make sure you can see every error.

This is super easy to do! The snippet below disables TrackJS if you access from localhost. Modify it below with whatever you use for development.

<!-- BEGIN TRACKJS -->
<script type="text/javascript">
window._trackJs = {
 token: 'YOUR_TOKEN_HERE',
 enabled: !(window.location.host.indexOf('localhost') >= 0)
};
</script>
<script type="text/javascript" src="https://cdn.trackjs.com/releases/current/tracker.js"></script>
<!-- END TRACKJS -->
Blackboxing

You may also notice that console messages and stacktraces contain references to tracker.js. This is a side-effect of our wrapping. If you’re developing in Chrome, you can exclude our script by Blackboxing it.

Ignoring Errors

Errors can arise in your application that may be beyond your control: maybe a buggy social or advertising provider, or maybe a buggy library you just have to use. Regardless, you just don”t want to see that problem everyday.

You can effectively hide all these errors using the onError configuration. It allows you to inspect errors before they are sent and decide if they should be sent. Returning a falsy value will prevent the error from sending.

<script>
window._trackJs = {
  token: 'YOUR_TOKEN_HERE',

  onError: function (payload, error) {
    // `payload` is the actual JSON data that will get sent to our servers
    // `error` is the actual JavaScript error object (if available)
    // We document the error payload in depth, check out the link below!

    // Maybe you don't want errors from admin parts of your site.
    var urlToIgnore = new RegExp("admin", "i");
    if(urlToIgnore.test(payload.url)){
      return false;
    }

    // Or maybe your getting some AJAX 401s you don't care about
    if(payload.message.indexOf("401") >= 0){
      return false;
    }

    // You can also ignore without inspecting the payload at all
    if(MyApplication.isSessionExpired()){
      return false;
    }

    return true; // Return any kind of truthy value here to allow transmission of error
  }
}
</script>
<script type="text/javascript" src="https://cdn.trackjs.com/releases/current/tracker.js"></script>

We have documented the entire error payload so you can see what kind of data you’ll have access to!

Modifying Errors

TrackJS may be capturing too much about your application. You can modify the contents of an error before it is sent using the onError configuration. Of course, the general shape of the object must remain same, or it will not process properly at our servers.

<script>
window._trackJs = {
  token: 'YOUR_TOKEN_HERE',
  onError: function (payload, error) {
    if (payload.message.indexOf("NSA") > 0){
      payload.message = "Redacted!";
    }

    // remove 401 network events, they happen all the time for us!
    payload.network = payload.network.filter(function (item){
      if(item.statusCode !== 401){
        return true;
      }
      else {
        return false;
      }
    });

    return true;
  }
}
</script>
<script type="text/javascript" src="https://cdn.trackjs.com/releases/current/tracker.js"></script>
The Sky is the Limit

The onError callback is very flexible. You have total control of the payload that gets sent to our servers. Feel free to experiment!

Adding Custom Metadata on Error

You can add custom metadata at any time using our top-level trackJs.addMetadata() API. This works well when you know the data you want to send before an error occurs (user locale, user subscription level, etc). But what if you want to add metadata that is specific to a single error? For example, maybe you want to additionally capture the name of the error. The name is something like “SyntaxError” or “TypeError”. This can be useful to track so you can group and filter by all instances of SyntaxError, for example.

window._trackJs = {
  token: "TOKEN",
  // other stuff
  onError: function (payload, error){
    // Add the error's name if present to the metadata array.
    payload.metadata.push({
      key: "Error Name",
      value: error.name || "Not Defined"
    });
    // Note that we expect both key and value to be strings.

    return true; // Ensure error gets sent
  }
}

Tracking Request/Response Payloads

For privacy reasons we don’t automatically capture the request or response payloads from network errors. However, if that’s something you wish to do, the following code provides a general outline of how that might be accomplished.

// First, you'll want to prevent TrackJS from *automatically* capturing network errors (as we do not track request/response in those circumstances)
// We will still log network requests, but they will just not cause errors to fire.
window._trackJs = {
  token: "YOUR_TOKEN_HERE",
  network: {
    error: false
  }
}
// ...
// then add some kind of global ajax handler; the following example uses jQuery.
$(document).ajaxError(function (evt, xhr, opts, errMsg) {
  // Log the error message
  // This will be visible and searchable in the telemetry timeline
  console.log(errMsg);
  // Or maybe request params
  console.log(opts.data);
  // Or log other things
  console.log(xhr.getAllResponseHeaders())
  var statusCode = xhr.status;
  var method = opts.type;
  var url = opts.url;
  // Send a nice message with method, status and url.
  trackJs.track(method + " " + statusCode + ": " + url);
});

Custom Serialization

By default, TrackJS serializes objects into a string you would expect to see in a log. However, sometimes we get it wrong. If you prefer to change how objects get represented in the log, you can override serialize with your custom implementation.

<script>
window._trackJs = {
  token: 'YOUR_TOKEN_HERE',
  serialize: function (item) {
    return YOUR_CUSTOM_SERIALIZER(item);
  }
}
</script>
<script type="text/javascript" src="https://cdn.trackjs.com/releases/current/tracker.js"></script>

Passive Tracking

This example shows how to configure TrackJS for a passive tracking environment, such as a third-party plugin or chrome module. In this case, you do not want to track everything on the page, as most events are not relevant to you. You only want to track events that you directly send into TrackJS.

<script>
  window._trackJs = {
    token: "YOUR_TOKEN_HERE",
    callback: { enabled: false },
    console: { enabled: false },
    network: { enabled: false },
    visitor: { enabled: false },
    window: { enabled: false }
  };
</script>
<script src="https://cdn.trackjs.com/releases/current/tracker.js"></script>

Then to record custom events:

trackJs.console.log("some thing happened", myState);

And to track an error:

try {
  // do your stuff
} catch (e) {
  trackJs.track(e);
}