Documentation

Developers

API References
Data Subject Request API

Data Subject Request API Version 1 and 2

Data Subject Request API Version 3

Platform API

Platform API Overview

Accounts

Apps

Audiences

Calculated Attributes

Data Points

Feeds

Field Transformations

Services

Users

Workspaces

Warehouse Sync API

Warehouse Sync API Overview

Warehouse Sync API Tutorial

Warehouse Sync API Reference

Data Mapping

Warehouse Sync SQL Reference

Warehouse Sync Troubleshooting Guide

ComposeID

Warehouse Sync API v2 Migration

Custom Access Roles API

Bulk Profile Deletion API Reference

Data Planning API

Group Identity API Reference

Calculated Attributes Seeding API

Pixel Service

Profile API

Events API

mParticle JSON Schema Reference

IDSync

Client SDKs
AMP

AMP SDK

Android

Initialization

Configuration

Network Security Configuration

Event Tracking

User Attributes

IDSync

Screen Events

Commerce Events

Location Tracking

Media

Kits

Application State and Session Management

Data Privacy Controls

Error Tracking

Opt Out

Push Notifications

WebView Integration

Logger

Preventing Blocked HTTP Traffic with CNAME

Linting Data Plans

Troubleshooting the Android SDK

API Reference

Upgrade to Version 5

Cordova

Cordova Plugin

Identity

Direct Url Routing

Direct URL Routing FAQ

Web

Android

iOS

Flutter

Getting Started

Usage

API Reference

iOS

Initialization

Configuration

Event Tracking

User Attributes

IDSync

Screen Tracking

Commerce Events

Location Tracking

Media

Kits

Application State and Session Management

Data Privacy Controls

Error Tracking

Opt Out

Push Notifications

Webview Integration

Upload Frequency

App Extensions

Preventing Blocked HTTP Traffic with CNAME

Linting Data Plans

Troubleshooting iOS SDK

Social Networks

iOS 14 Guide

iOS 15 FAQ

iOS 16 FAQ

iOS 17 FAQ

iOS 18 FAQ

API Reference

Upgrade to Version 7

React Native

Getting Started

Identity

Roku

Getting Started

Identity

Media

Unity

Upload Frequency

Getting Started

Opt Out

Initialize the SDK

Event Tracking

Commerce Tracking

Error Tracking

Screen Tracking

Identity

Location Tracking

Session Management

Xbox

Getting Started

Identity

Web

Initialization

Configuration

Content Security Policy

Event Tracking

User Attributes

IDSync

Page View Tracking

Commerce Events

Location Tracking

Media

Kits

Application State and Session Management

Data Privacy Controls

Error Tracking

Opt Out

Custom Logger

Persistence

Native Web Views

Self-Hosting

Multiple Instances

Web SDK via Google Tag Manager

Preventing Blocked HTTP Traffic with CNAME

Facebook Instant Articles

Troubleshooting the Web SDK

Browser Compatibility

Linting Data Plans

API Reference

Upgrade to Version 2 of the SDK

Xamarin

Getting Started

Identity

Web

Alexa

Media SDKs

iOS

Web

Android

Quickstart
Android

Overview

Step 1. Create an input

Step 2. Verify your input

Step 3. Set up your output

Step 4. Create a connection

Step 5. Verify your connection

Step 6. Track events

Step 7. Track user data

Step 8. Create a data plan

Step 9. Test your local app

HTTP Quick Start

Step 1. Create an input

Step 2. Create an output

Step 3. Verify output

iOS Quick Start

Overview

Step 1. Create an input

Step 2. Verify your input

Step 3. Set up your output

Step 4. Create a connection

Step 5. Verify your connection

Step 6. Track events

Step 7. Track user data

Step 8. Create a data plan

Java Quick Start

Step 1. Create an input

Step 2. Create an output

Step 3. Verify output

Node Quick Start

Step 1. Create an input

Step 2. Create an output

Step 3. Verify output

Python Quick Start

Step 1. Create an input

Step 2. Create an output

Step 3. Verify output

Web

Overview

Step 1. Create an input

Step 2. Verify your input

Step 3. Set up your output

Step 4. Create a connection

Step 5. Verify your connection

Step 6. Track events

Step 7. Track user data

Step 8. Create a data plan

Server SDKs

Node SDK

Go SDK

Python SDK

Ruby SDK

Java SDK

Tools

mParticle Command Line Interface

Linting Tools

Smartype

Guides
Partners

Introduction

Outbound Integrations

Outbound Integrations

Firehose Java SDK

Inbound Integrations

Kit Integrations

Overview

Android Kit Integration

JavaScript Kit Integration

iOS Kit Integration

Compose ID

Data Hosting Locations

Glossary

Migrate from Segment to mParticle

Migrate from Segment to mParticle

Migrate from Segment to Client-side mParticle

Migrate from Segment to Server-side mParticle

Segment-to-mParticle Migration Reference

Rules Developer Guide

API Credential Management

The Developer's Guided Journey to mParticle

Guides

Getting Started

Create an Input

Start capturing data

Connect an Event Output

Create an Audience

Connect an Audience Output

Transform and Enhance Your Data

Platform Guide
The New mParticle Experience

The new mParticle Experience

The Overview Map

Observability

Observability Overview

Observability User Guide

Observability Span Glossary

Introduction

Data Retention

Connections

Activity

Live Stream

Data Filter

Rules

Tiered Events

mParticle Users and Roles

Analytics Free Trial

Troubleshooting mParticle

Usage metering for value-based pricing (VBP)

Analytics

Introduction

Setup

Sync and Activate Analytics User Segments in mParticle

User Segment Activation

Welcome Page Announcements

Settings

Project Settings

Roles and Teammates

Organization Settings

Global Project Filters

Portfolio Analytics

Analytics Data Manager

Analytics Data Manager Overview

Events

Event Properties

User Properties

Revenue Mapping

Export Data

UTM Guide

Query Builder

Data Dictionary

Query Builder Overview

Modify Filters With And/Or Clauses

Query-time Sampling

Query Notes

Filter Where Clauses

Event vs. User Properties

Group By Clauses

Annotations

Cross-tool Compatibility

Apply All for Filter Where Clauses

Date Range and Time Settings Overview

Understanding the Screen View Event

Analyses

Analyses Introduction

Segmentation: Basics

Getting Started

Visualization Options

For Clauses

Date Range and Time Settings

Calculator

Numerical Settings

Segmentation: Advanced

Assisted Analysis

Properties Explorer

Frequency in Segmentation

Trends in Segmentation

Did [not] Perform Clauses

Cumulative vs. Non-Cumulative Analysis in Segmentation

Total Count of vs. Users Who Performed

Save Your Segmentation Analysis

Export Results in Segmentation

Explore Users from Segmentation

Funnels: Basics

Getting Started with Funnels

Group By Settings

Conversion Window

Tracking Properties

Date Range and Time Settings

Visualization Options

Interpreting a Funnel Analysis

Funnels: Advanced

Group By

Filters

Conversion over Time

Conversion Order

Trends

Funnel Direction

Multi-path Funnels

Analyze as Cohort from Funnel

Save a Funnel Analysis

Explore Users from a Funnel

Export Results from a Funnel

Cohorts

Getting Started with Cohorts

Analysis Modes

Save a Cohort Analysis

Export Results

Explore Users

Saved Analyses

Manage Analyses in Dashboards

Journeys

Getting Started

Event Menu

Visualization

Ending Event

Save a Journey Analysis

Users

Getting Started

User Activity Timelines

Time Settings

Export Results

Save A User Analysis

Dashboards

Dashboards––Getting Started

Manage Dashboards

Dashboard Filters

Organize Dashboards

Scheduled Reports

Favorites

Time and Interval Settings in Dashboards

Query Notes in Dashboards

User Aliasing

Analytics Resources

The Demo Environment

Keyboard Shortcuts

Tutorials

Analytics for Marketers

Analytics for Product Managers

Compare Conversion Across Acquisition Sources

Analyze Product Feature Usage

Identify Points of User Friction

Time-based Subscription Analysis

Dashboard Tips and Tricks

Understand Product Stickiness

Optimize User Flow with A/B Testing

User Segments

APIs

User Segments Export API

Dashboard Filter API

IDSync

IDSync Overview

Use Cases for IDSync

Components of IDSync

Store and Organize User Data

Identify Users

Default IDSync Configuration

Profile Conversion Strategy

Profile Link Strategy

Profile Isolation Strategy

Best Match Strategy

Aliasing

Data Master
Group Identity

Overview

Create and Manage Group Definitions

Introduction

Catalog

Live Stream

Data Plans

Data Plans

Blocked Data Backfill Guide

Personalization
Predictive Attributes

Predictive Attributes Overview

Create Predictive Attributes

Assess and Troubleshoot Predictions

Use Predictive Attributes in Campaigns

Predictive Audiences

Predictive Audiences Overview

Using Predictive Audiences

Introduction

Profiles

Calculated Attributes

Calculated Attributes Overview

Using Calculated Attributes

Create with AI Assistance

Calculated Attributes Reference

Audiences

Audiences Overview

Real-time Audiences

Standard Audiences

Journeys

Journeys Overview

Manage Journeys

Download an audience from a journey

Audience A/B testing from a journey

Journeys 2.0

Warehouse Sync

Data Privacy Controls

Data Subject Requests

Default Service Limits

Feeds

Cross-Account Audience Sharing

Approved Sub-Processors

Import Data with CSV Files

Import Data with CSV Files

CSV File Reference

Glossary

Video Index

Analytics (Deprecated)
Identity Providers

Single Sign-On (SSO)

Setup Examples

Settings

Debug Console

Data Warehouse Delay Alerting

Introduction

Developer Docs

Introduction

Integrations

Introduction

Rudderstack

Google Tag Manager

Segment

Data Warehouses and Data Lakes

Advanced Data Warehouse Settings

AWS Kinesis (Snowplow)

AWS Redshift (Define Your Own Schema)

AWS S3 Integration (Define Your Own Schema)

AWS S3 (Snowplow Schema)

BigQuery (Snowplow Schema)

BigQuery Firebase Schema

BigQuery (Define Your Own Schema)

GCP BigQuery Export

Snowflake (Snowplow Schema)

Snowplow Schema Overview

Snowflake (Define Your Own Schema)

APIs

Dashboard Filter API (Deprecated)

REST API

User Segments Export API (Deprecated)

SDKs

SDKs Introduction

React Native

iOS

Android

Java

JavaScript

Python

Object API

Developer Basics

Aliasing

Rules Developer Guide

mParticle’s Rules are JavaScript functions that manipulate an incoming batch object from an mParticle input. See mParticle’s Platform Guide for help setting up rules in the mParticle dashboard.

General format

Rules take the form of an AWS Lambda function, running in Node.js 16. The function takes an incoming batch argument to be manipulated and a context argument containing immutable metadata. The context argument is required, but for an mParticle rule is effectively null.

The callback takes a message and a data output. For mParticle Rules, the message will always be null. The output should either be an object in the same format as the original batch argument, or null.

exports.handler=(batch,context,callback)=>{
    //Do something with batch
    callback(null, batch); // or callback(null, null); to drop the batch completely
}

Note that standard AWS Lambda naming convention calls for (event,context,callback); here we have used (batch,context,callback) to avoid confusion with mParticle’s event object.

While all rules have the same basic syntax, there are two main use cases for rules:

  • working with the events array of a batch
  • working with any other properties of the batch.

Non-events rules

There are two basic kinds of non-event rules:

The first is a simple ‘filter’. Based on some attribute/s of the batch, the callback either contains the original batch object, unaltered, or null, effectively dropping the batch, altogether:

exports.handler=(batch,context,callback)=>{
/* 
A support feed contains batches from internal and external users. 
We can create a rule to drop batches from internal users.
*/    
    if(batch.user_attributes.internal) {
        callback(null, null);
    }
    else{
        callback(null, batch);
    }
};

Alternatively, the callback can contain a modified version of the original batch, with some attributes added, changed or dropped.

exports.handler=(batch,context,callback)=>{
/* 
An input has firstname and lastname attributes for a user.
Our output platform expects a full name, so we can use a rule to create one.
*/    
    if(batch.user_attributes.$firstname && batch.user_attributes.$lastname) {
        var firstname = batch.user_attributes.$firstname;
        var lastname = batch.user_attributes.$lastname;
        batch.user_attributes.name = `${firstname} ${lastname}`;
    }
    callback(null, batch);

};

If you want to update a user attribute via a rule and that rule is connected to a platform input (Android, iOS, Web, Roku, etc.), you must use user attribute update events in the rule.

The following example of an inbound rule adds a new user attribute to the user_attributes JSON in the event batch. Because the data is sent via platform input (SDK), the example also includes a user attribute change (UAC) event in the event batch for the new user attributes being set.

// User attribute added to user_attributes
batch.user_attributes["foo"] = "this is the new value";

// UAC event added to events 
batch.events.push(
{
   "data":{
      "user_attribute_name":"foo",
      "new":"this is the new value",
      "old":"this is an old value", //this is optional
      "deleted":false,
      "is_new_attribute":true
   },
   "event_type":"user_attribute_change"
}
);

If the UAC event isn’t present in SDK batches, the user attribute shows up in Live Stream, in event batches in the User Activity view, and possibly downstream, but it won’t be written to the user’s mParticle profile. Thus, it won’t be usable for audiences or journeys.

UAC events aren’t required for server-to-server data. An SDK uploads an event whenever a user attribute changes to denote new attributes, changing attributes, and removed attributes. This allows for calculation of the current user attribute state for each event within an mParticle upload.

Event-focused rules

The batch object contains an events array, which can have any number of events. If you want to handle each event individually, you will need to define a handler function and use it to iterate over the events array.

exports.handler=(batch,context,callback)=>{
/* 
An input sends events with the event name 'Signup'. 
We can create a rule to change it to 'subscribe', to tailor it to a specific Output service.
*/
    function event_handler(event) {
        if (event.data.event_name === 'Signup') {
            event.data.event_name = 'subscribe';
        }
     	return event;
    }
    
    var events = batch.events;
    var newEvents = [];
    
    events.forEach(function(currentEvent){
    	try { 
    	    newEvents.push(event_handler(currentEvent));
    	}
    	catch(err){ }
    });
    
    batch.events = newEvents;
    
    callback(null, batch);
};

All Output vs Specific Output rules

Rules can be applied in two places. ‘All Output’ rules are applied first, and their output is passed along to all Output services connected to that input. ‘Specific Output’ Rules are applied as part of a particular Input/Output connection and affect only that Output service.

In most ways the two types of rules operate in the same way. Both take the same arguments and return a batch object in the same format. However, different fields can be accessed and altered in ‘All Outputs’ and ‘Specific Outputs’ rules. See Batch format for details.

Error handling

When creating a rule in the mParticle dashboard, you must select a Failure Action. This determines what will happen if your rule throws an unhandled exception.

  • If you choose Discard, an unhandled exception will cause your rule return null, effectively dropping the batch.
  • If you choose Proceed, an unhandled exception will cause your rule to return the unaltered batch object, proceeding as if the rule had not been applied.

Regardless of which option you choose, it’s best practice to handle all exceptions in your code, rather than falling back on the above defaults. This is especially true if your rule deals with events, where an unhandled exception from just one event could lead to all events in the batch being dropped.

Batch format

See the main mParticle docs for full JSON batch examples. There are a few limitations on what is available and what can be changed in Rules:

Limitations applying to all Rules:

  • Unique IDs for the Batch (batch.batch_id) and for each event (event.event_id) cannot be altered.
  • Any null in the events array will cause a serialization error. If you want to drop individual events, make sure your handler does not push null to the event array.

Limitations applying only to ‘All Outputs’ Rules:

  • Unique IDs for the Batch (batch.batch_id) and for each event (event.event_id) will not be populated.
  • IP address (batch.ip) cannot be accessed in a rule. If a value is set for batch.ip it will be accepted only if it is a valid IP address.
  • The Application Info (batch.application_info) object cannot be accessed or altered.
  • Any changes made to the Deleted Attributes object (batch.deleted_user_attributes) will not be applied to the user profile.

Best practices for Node JS rules

AWS supports multiple Node runtime versions. If using Node for your Rule, be sure to select a runtime that supports the Javascript features you want to use.

To control costs, you can combine multiple transformations into a single rule.

The Batch object is deeply nested. Be careful when accessing nested keys, as the rule will error if one of the parent keys does not exist. Likewise, different event types have different properties. If part of your rule only applies to a specific event type, wrap it in a conditional statement.

/* 
If applied to an event that is not a Commerce event, 
this condition will cause an error and prevent 
the entire batch from being processed.
*/
if (event.data.product_action.action === "add_to_cart") {
    //do something
}

/* 
You can add a condition to only apply this part of 
the rule to Commerce events.
*/
if (event.event_type === "commerce_event") {
    if (event.data.product_action.action === "add_to_cart") {
        //do something
    }
}

/* 
The above rule will still fail if the commerce event does 
not contain a product action. To be safer, check each nested key.
*/
if (event.event_type === "commerce_event") {
    if (event.data && event.data.product_action && event.data.product_action.action === "add_to_cart") {
        //do something
    }
}

While the Rules UI supports two basic error handling mechanisms (either dropping the batch or forwarding it as is), it’s preferable for your rule to handle errors wherever possible to avoid unexpected behavior. If your rule applies multiple transformations to a batch, wrap each section in a try...catch statement so that an error in one part of your rule doesn’t stop other parts from being applied.

/* 
This event handler function has two parts to deal with commerce events and custom events. 
By using try...catch, we ensure that, if one part of the rule causes an unforseen error, 
the other part can still be applied.
*/
function event_handler(event) {
    try {
        if (event.event_type === "commerce_event") {
            if (event.data && event.data.product_action && event.data.product_action.action === "add_to_cart") {
                //do something
            }
        }  
    }
    catch (error) {
        // handle error
    }

    try {
        if (event.event_type === "custom_event") {
            if (event.data && event.data.event_name && event.data.event_name === "level_up") {
                event.data.event_name = "increase_level";
            }
        }  
    }
    catch (error) {
        // handle error
    }
    return event;
}

Examples

Event renamer

Converts event names from an input platform still using an older version of those names.

exports.handler = (batch, context, callback) => {   
    // Define mapping of legacy names to new names
    const mappings = {
        "legacy_name1": "new_name1",
        "legacy_name2": "new_name2",
        "legacy_name3": "new_name3"
    };

    // If the event name is in mappings, update it to the new name
    function rename_test_events(eventItem, mappings) {
        const keys = Object.keys(mappings);
        if (keys.indexOf(eventItem.data.event_name) != -1) {
            eventItem.data.event_name = mappings[eventItem.data.event_name];
        }
    }

    // Create updated events array
    const newEvents = []
    batch.events.forEach(item => {
        try {
            rename_test_events(item, mappings);
            newEvents.push(item)
        }
        catch (err) { } // if an error occurs, exclude the event from the updated events array
    });

    // Replace original events with updated events
    batch.events = newEvents;
    callback(null, batch);
};

Multiple transformations

Apply multiple transformations to events and user attributes within a single rule.

exports.handler = (batch, context, callback) => {
    // Change "United States" to "USA"
    function changeCountryName(data) {
        if (!data.user_attributes || !data.user_attributes.$Country) {
            return;
        }

        const countryLower = data.user_attributes.$Country.toLowerCase();

        if (countryLower === 'united states' || countryLower === 'united states of america') {
            data.user_attributes.$Country = 'USA';
        }
    }

    // If an event name is received as "Play Video", change it to "Viewed Video"
    function rename_test_events(eventItem) {
        if (eventItem.data.event_name === 'Play Video') {
            eventItem.data.event_name = 'Viewed Video';
        }
    }

    // Create an attribute to record speed in seconds based on an existing "timing" attribute
    function create_speed_attribute(eventItem) {
        if (eventItem.data.custom_attributes && eventItem.data.custom_attributes.timing) {
            eventItem.data.custom_attributes.speed = eventItem.data.custom_attributes.timing / 1000;
        }
    }

    // Update events
    newEvents = [];
    batch.events.forEach(item => {
        // Basic error handling is included here, to avoid dropping or passing through
        // a whole batch due to errors processing one event.
        try {
            rename_test_events(item);
            create_speed_attribute(item);
            newEvents.push(item);
        }
        catch (err) { }
    });
    batch.events = newEvents;

    // Update batch
    changeCountryName(batch);

    callback(null, batch);
};

Was this page helpful?

    Last Updated: November 20, 2024