Javascript Enrichment

Short Description

This enrichment lets you write a JavaScript function which is executed in the Enrichment process for each enriched event. Use this enrichment to apply your own business logic to your enriched events at the row-level

Overview

The custom JavaScript enrichment is a great example of the power of Snowplow Insights. Through this functionality the ability to “data widen” your events at the row level, means that if you have access to a unique data set that can be used to give a higher level of detail and context around certain events you are collecting, you can insert them at this enrichment step before writing to your data store.

Since your company has a unique set of customers and likely a unique set of data points that speak towards the behavioural interactions customers have with your site or applications, the more information you can capture at the time of the event means the more insight you can find in the analysis of those events.

Example

Although the use cases for this enrichment can be endless, they don’t need to only serve analytics purposes. A very useful case might be in anti-spoofing for instance. You might want to make sure that the events being sent over are from your app or website rather than one spoofed by a hacker.

To do so you might write a Javascript function that checks if a secret key is valid server side, and only then set the event with the correct “app_id” variable that denotes it is a valid event from your property.

Taking this example further, you could do something like notify the user that sent the event that they are likely on a spoofing website.

Here’s an example snippet of code relating to the above:

const SECRET_APP_ID = "Joshua";
    
/**
 * Performs two roles:
 * 1. If this is a server-side event, we
 *    validate that the app_id is our
 *    valid secret. Prevents spoofing of
 *    our server-side events
 * 2. If app_id is not null, return a new
 *    Acme context, derived_app_id, which
 *    contains the upper-cased app_id
 */
 
function process(event) {
    var appId = event.getApp_id();
  
    if (platform == "server" && appId != SECRET_APP_ID) {
        throw "Server-side event has invalid app_id: " + appId;
    }
  
    if (appId == null) {
        return [];
    }
  
    var appIdUpper = new String(appId.toUpperCase());
    return [ { schema: "iglu:com.acme/derived_app_id/jsonschema/1-0-0",
               data:  { appIdUpper: appIdUpper } } ];
}