Advanced Features

Getting started with Raygun4JS is straightforward using the basic installation (see the Crash Reporting and Real User Monitoring installation guides), but sometimes you want additional options and functionality.

Here you will find advanced features for both Crash Reporting and Real User Monitoring (RUM) with Raygun4JS. These options apply to all JavaScript-based Raygun implementations that use Raygun4JS and expose its functionality. Please contact support if the functionality avaliable for a specific framework is unclear.


Post-installation

You have completed the basic installation of Raygun and you are successfully seeing data on your dashboard, so what's next?

JavaScript can be a noisy language when it comes to errors, as third party scripts and plugins can contribute many. If this is the case, you might want to alter your notification settings to ensure you're not getting bombarded with notifications while using Crash Reporting.

Raygun allows you to curate your error reports, narrowing it down to the issues you care about most by using our workflow tools. Raygun is not a simple logging tool; you will get the most out of it by utilizing the tools and features avaliable to you. See Alerting, Crash Reporting Integrations, Error grouping, Filtering error groups, Error statuses, Inbound filters, and more!

If you have enabled Real User Monitoring for your application, user sessions will be tracked automatically. You can then view the performance of pages within user sessions and make targeted optimizations. Users will be anonymous until you set up Customers to identify authenticated users of your app.


If you would like to defer the loading of the Raygun snippet, you can do so by adding the defer attribute to the script tag.

This will ensure the script is loaded after the page has finished loading, but before the DOMContentLoaded event is fired.

We strongly recommend that you place the script tag for the provider snippet first and mark all of your other scripts with defer (but not async). This will guarantee that the Raygun4JS provider is executed before any of the others.

Without doing this, you will find that it's possible for errors to occur before Raygun has loaded, which means you'll lose visiblity into these issues.


To configure the Raygun4JS provider, pass in an options object. For example:

rg4js('options', {
  ignoreAjaxAbort: true,
  ignoreAjaxError: true,
  debugMode: true,
  ignore3rdPartyErrors: false,
  wrapAsynchronousCallbacks: true,
  excludedHostnames: ['localhost', '\.dev'],
  excludedUserAgents: ['PhantomJS', 'MSIE'],
  disableErrorTracking: false,
  disablePulse: false,
  pulseMaxVirtualPageDuration: 1800000,
  pulseIgnoreUrlCasing: false,
  automaticPerformanceCustomTimings: false
});

The following options can be configured:

ignoreAjaxAbort - User-aborted Ajax calls result in errors - if this option is true, these will not be sent.

ignoreAjaxError - Ajax requests that return error codes will not be sent as errors to Raygun if this option is true.

debugMode - Raygun4JS will log to the console when sending errors.

ignore3rdPartyErrors - ignores any errors that have no stack trace information. This will discard any errors that occur completely within 3rd party scripts - if code loaded from the current domain called the 3rd party function, it will have at least one stack line and will still be sent. This option removes nonsense 'Script Errors' from your Raygun dashboard. Fore more details, check Ignore 3rd-Party Errors Algorithm

wrapAsynchronousCallbacks - disables wrapping of async setTimeout/setInterval callbacks when set to false. Defaults to true. This option is respected when attach() is called.

excludedHostnames - Prevents errors from being sent from certain hostnames (domains) by providing an array of strings or RegExp objects (for partial matches). Each should match the hostname or top level domain (TLD) that you want to exclude. Note that protocols are not tested.

excludedUserAgents - Prevents errors from being sent from certain clients, based on their user agent string. Pass in an array of strings or RegExp objects. Useful for ignoring headless browsers in unit testing, or old/problematic clients.

disableAnonymousUserTracking - Prevent user data being sent for anonymous users (those where setUser hasn't been called).

disableErrorTracking - Prevent all errors from being sent.

disablePulse - Prevent Real User Monitoring events from being sent.

apiEndpoint - A string URI containing the protocol, domain and port (optional) where all payloads will be sent to. This can be used to proxy payloads to the Raygun API through your own server. When not set, this defaults internally to the Raygun API, and for most usages you won't need to set this.

clientIp - A string containing the client's IP address. RUM requests will be associated to this IP address when set. Particularly useful when proxying payloads to the Raygun API using the apiEndpoint option and maintaining RUM's geographic lookup feature.

Note: navigator.sendBeacon is used to send RUM payloads when a page is unloading. As such, the clientIp feature will not work with payloads sent when a page is unloading.

pulseMaxVirtualPageDuration - The maximum time a virtual page can be considered viewed, in milliseconds (defaults to 30 minutes).

pulseIgnoreUrlCasing - Ignore URL casing when sending data to Real User Monitoring.

captureUnhandledRejections - Automatically report errors relating to unhanded promise rejections. Browser support for this option is dependant on the unhandledrejection event.

setCookieAsSecure - If cookies are being used (only used on browsers which don't support localStorage or sessionStorage) then they will be created using the ; secure flag and thus cookies only work on HTTPS.

captureMissingRequests - RUM uses the window.performance API to track XHR timing information and (depending on the browser) not all non-2XX XHR timings are recorded by this API. This option enables the tracking of these missing XHR's calls by tracking the difference between send & success XHR handlers. This is not enabled by default due these timings being as accurate as the performance API.

automaticPerformanceCustomTimings - When enabled Raygun4JS will track each performance.measure call as a custom timing entry. This enables developers to use a native API for tracking performance timings. More information about performance.measure can be found on MDN.


Raygun4JS listens for errors reported by the onerror handler. However, sometimes you will want to send custom handled errors manually, either in an exception handler or from within a try/catch block. You can use the following code to do so:

rg4js('send', {
   error: new Error('my error message'),
});

Your Raygun dashboard can display tags for specific errors you want to identify, or filter by. Perhaps these are issues affecting your billing pages or you want to be able to identify when errors come from a specific part of your stack. These are arrays of strings or numbers. This is done in a similar way to attaching custom data, like so:

// After initialization
rg4js('withTags', ['tag1', 'tag2']);

// When manually sending a error
rg4js('send', {
  error: e,
  tags: ['tag3']
});

You can optionally configure Customers, either anonymously or non-anonymously (if your app has the concept of a logged-in user and their data available). Here's an example of how to set it up with Raygun4JS:

rg4js('setUser', {
  identifier: 'hello@raygun.com', // A unique ID, email address, or another ID such as a UUID
  isAnonymous: false, // Indicates whether the user is anonymous or not
  email: 'hello@raygun.com', // Optional 
  firstName: 'Ronald', // Optional
  fullName: 'Ronald Raygun', // Optional
  uuid: 'BAE62917-ACE8-ab3D-9287-B6A33B8E8C55' // Optional device identifier
});

By default, Raygun4JS assigns a unique anonymous ID for the current user. This is stored in LocalStorage or as a Cookie (if local storage is not available).

To reset the anonymous user data, you can call:

rg4js('getRaygunInstance').resetAnonymousUser();
rg4js('options', { disableAnonymousUserTracking: true });

When a user has logged out of your application, you can remove their data from all subsequent crash reports with setUser() like so:

rg4js('setUser', {
  isAnonymous: true
});

The Raygun object has a withCustomData() function where you can pass in JavaScript objects that will be sent with each error that occurs. This allows you to provide any useful data that is global or in scope.

There are two ways to do this:

On initialization:

Custom data can be attached to all error instances sent to Raygun by calling the withCustomData() method:

rg4js('withCustomData', { foo: 'bar' });

note: When providing custom data be careful to ensure that objects passed do not contain circular references.

During a send:

Custom data can also be passed when manually sending errors to Raygun. This allows you to add in-scope variables to provide you with more context about the error.

// When manually sending an error
rg4js('send', {
  error: e,
  customData: { foo: 'bar' }
});

// The customData key accepts both array and object formats
rg4js('send', {
  error: e,
  customData: [{ foo: 'bar' }]
});

note: When both methods of passing custom data are used both objects passed are merged together and will send with each error instance.

To send the state of variables at the time an error occurs, you can pass withCustomData() a function. This needs to return an object. For example:

var desiredNum = 1;

function generateCustomData() {
 return { num: desiredNum };
}

rg4js('withCustomData', generateCustomData);

generateCustomData() will be called when Raygun4JS is about to send an error, which will construct the custom data. This will be merged with any custom data provided on a Raygun.send() call.


You can control custom grouping for error instances by passing in a callback. This will override the automatic grouping and be used to group error instances together. Errors with the same key will be placed within the same error group. The callback's signature should take in the error payload, stackTrace and options and return a string, ideally 64 characters or less. If the callback returns null or a non-string the error will be grouped using Raygun's server side grouping logic (this can be useful if you only wish to use custom grouping for a subset of your errors).

var groupingKeyCallback = function (payload, stackTrace, options) {
  // Inspect the above parameters and return a hash derived from the properties you want
  return payload.Details.Error.Message; // Naive message-based grouping only
};

rg4js('groupingKey', groupingKeyCallback);

You can set a version for your app by calling:

rg4js('setVersion', '1.0.0.0');

This will allow you to filter the errors in your Raygun dashboard by that version. You can also select only the latest version, to ignore errors that were triggered by previous versions of your code. The parameter should be a string in the format x.x.x if you want to get the version sorting in Raygun to work nicely. Where x is a non-negative integer.


rg4js('onBeforeSend', function (payload) {
  return payload;
});

Call this function and pass in a function which takes one parameter (see the example below). This callback function will be called immediately before the payload is sent. The one parameter it gets will be the payload that is about to be sent. Thus from your function you can inspect the payload and decide whether or not to send it.

From the supplied function, you should return either the payload, or return false.

If your function returns a truthy object, Raygun4JS will attempt to send it as supplied. Thus, you can mutate it as per your needs - preferably only the values if you wish to filter out data that is not taken care of by filterSensitiveData(). You can also of course return it as supplied.

If, after inspecting the payload, you wish to discard it and abort the send to Raygun, simply return false.

For example:

var myBeforeSend = function (payload) {
  console.log(payload); // Modify the payload here if necessary
  return payload; // Return false here to abort the send
}

rg4js('onBeforeSend', myBeforeSend);
rg4js('onAfterSend', function (xhrResponse) {
  // Inspect the XHR response here
});

Call this function and pass in a function which takes one parameter (see the example below). This callback function will be immediately called after the XHR request for a Crash Reporting or RUM event responds successfully, or errors out (its onerror was called). You can inspect the one parameter, which is the XHR object containing the HTTP response data.

rg4js('onBeforeSendRUM', function (payload) {
  return payload;
});

Call this function and pass in a function which takes one parameter (see the example below). This callback function will be called immediately before any Real User Monitoring events are sent. The one parameter it gets will be the payload that is about to be sent. Thus from your function you can inspect the payload and decide whether or not to send it.

From the supplied function, you should return either the payload (intact or mutated as per your needs), or false.

If your function returns a truthy object, Raygun4JS will attempt to send it as supplied. Thus, you can mutate it as per your needs. You can also of course return it as supplied.

If, after inspecting the payload, you wish to discard it and abort the send to Raygun, simply return false.

Example:

var myBeforeSend = function (payload) {  
  console.log(payload); // Modify the payload here if necessary  
  return payload; // Return false here to abort the send  
}

rg4js('onBeforeSendRUM', myBeforeSend);
rg4js('onBeforeXHR', function (xhr) {
  // Mutate the xhr parameter as per your needs
});

Call this function when you want control over the XmlHttpRequest object that is used to send error payloads to the API. Pass in a callback that receives one parameter (which is the XHR object). Your callback will be called after the XHR object is opened, immediately before it is sent.

For instance, you can use this to add custom HTTP headers.

As above for custom data, withTags() can now also accept a callback function. This will be called when the provider is about to send, to construct the tags. The function you pass to withTags() should return an array (ideally of strings/Numbers/Dates).

rg4js('withTags', function() {
  return ['tag1', 'tag2']
});

When offline saving is enabled, errors are caught when there is no network activity and are then saved in LocalStorage. Once connectivity is regained, previously saved errors will then be sent. This is useful in environments where a users' internet connection is not constant.

Offline saving is disabled by default. To enable the offline saving option, call the rg4js() method with saveIfOffline, as shown below:

rg4js('saveIfOffline', true);

If an error is caught and no network connectivity is available, or if the request times out after 10s, the error will be saved to LocalStorage.


Browser behavior varies for errors occurring in scripts located on a domain other than the origin. Many of these will be listed in Raygun as 'Script Error', or will contain poor stack traces. There are a few steps you can take to prevent third party errors from being sent to your Raygun application.

Raygun's ignore3rdPartyErrors option targets and filters out these errors.

note: See the whitelisting domains feature to enable the transmission of errors from certain domains.

rg4js('options', { ignore3rdPartyErrors: true });

This option will also block errors that occur in scripts injected into your site by browser extensions, bots or crawlers.

Permanently ignore third party error groups as they occur to prevent them being sent to Raygun in the future.

Set up inbound filters to filter out any patterns in 3rd party errors and prevent them from being sent to Raygun.

Use onBeforeSend() to inspect error payloads and determine if it's a third party error and should be rejected.


If your application needs to send requests through a proxy, you can configure Raygun4JS to point at a different API endpoint. Requests made will then need to be forwarded to the Raygun API.

By default Raygun4JS sends requests to https://api.raygun.io. To change this endpoint by using the apiEndpoint option and setting it to a URI which points to your proxy. The URI needs to contain the protocol, domain and (optionally) a port. Payloads will then be sent to this address instead of https://api.raygun.io.

rg4js('options', {
  apiEndpoint: 'https://raygun.mydomain.com', // Change to your proxy's endpoint 
});

Raygun4JS sends Crash Reporting error payloads and Real User Monitoring session payloads to the following two endpoints. When configuring your proxy you need to make sure requests made to the following URIs and then forwarded to our API with their headers intact.

  • Crash Reporting sends error payloads via POST to https://api.raygun.io/entries
  • Real User Monitoring sends session payloads via POST to https://api.raygun.io/events

Real User Monitoring uses the IP address sent with requests to find the location of your users so you can understand the performance impact. When forwarding information through a proxy this functionality can break as the IP sent will be from your proxy's machine. To maintain this functionality you can either:

1. Set the x-forwarded-for to send the users IP with the proxy.

When forwarding requests via a proxy onto the Raygun API you can attach a x-forwarded-for header to each payload. This value would be the user's IP address and the Raygun API will then associate these payloads with that IP provided.

2. Use the clientIp option.

If you can't configure the proxy to attach a new header you can use the clientIp option in Raygun4JS to set your user's IP address. This will attach a x-remote-address header to each request associating each payload to the IP provided. See the example below for an example of how this can work:

rg4js('clientIp', '192.168.0.2'); // Replace the IP with your user's IP address

You can blacklist keys to prevent their values from being sent in the error payload, by providing an array of key names:

rg4js('filterSensitiveData', ['password', 'credit_card']);

If any key matches one in the input array, its value will be replaced with the string [removed by filter].

By default, this is applied to the UserCustomData object only (legacy behavior). To apply this to any key-value pair, you can change the filtering scope:

rg4js('setFilterScope', 'all'); // Filter any key in the payload
rg4js('setFilterScope', 'customData'); // Just filter the custom data (default)

You can also pass RegExp objects in the array to filterSensitiveData, for controllable matching of keys:

var creditCardDataRegex = /credit\D*/; // Remove any keys that begin with 'credit'
rg4js('filterSensitiveData', [creditCardDataRegex]);

Raygun4JS features sourcemap support through the transmission of line and column numbers for errors, where available. See the sourcemaps documentation for more information.


Allow transmission of errors to Raygun from certain domains, accepting those domains as an array of strings:

rg4js('options', { ignore3rdPartyErrors: true });
rg4js('whitelistCrossOriginDomains', ['code.jquery.com']);

This can be used to allow errors from remote sites, subdomains and CDNs when the ignore3rdPartyErrors feature is enabled.

To get full stack traces from cross-origin domains or subdomains, these requirements should be met:

  • The remote domain should have Access-Control-Allow-Origin set (to include the domain where raygun4JS is loaded from).
  • The script tag must also have crossOrigin="Anonymous" set.
  • Recent versions of Firefox (>= 31) will transmit errors from remote domains with full stack traces if the header is set.

In Chrome, if the origin script tag and remote domain do not meet these requirements the cross-origin error will not be sent.

Other browsers may send on a best-effort basis (version dependent) if some data is available, but potentially without a useful stacktrace. The provider will cancel the send if no data is available.


The provider is open source and available at the Raygun4JS repository.