Transformation Templates

Use prebuilt transformations to implement specific use cases on your event data.

RudderStack’s transformation templates provide prebuilt JavaScript functions that you can use to create transformations and implement use cases on your event data. These include event filtering and sampling, replacing or hashing PII (Personally Identifiable Information), anonymizing IPs, and more.

info
Currently, transformation templates are available only for JavaScript. Python support (applicable for Growth/Enterprise customers) is coming soon.

Using templates

To use transformation templates, go to Collect > Transformations and click Create Transformation.

Under Transformation templates, select the prebuilt template depending on your use case:

Choose a template

To write a transformation from scratch, click Custom transformation.

Transformation templates

RudderStack provides the following prebuilt templates:

Templates for PII management

Use the following templates to easily apply rules for PII management.

IP Anonymization

This transformation changes the last octet of the IP address to zero. For example, the IP 12.214.31.144 is transformed to 12.214.31.0. This protects the privacy rights of your users and reduces the risk of accidentally disclosing their IP addresses.

The transformation is shown below:

export function transformEvent(event, metadata) {
  const ip = event.request_ip;
  if (ip) event.request_ip = ip.replace(/\d{1,3}$/, "0");
  return event;
}

Replace PII

This transformation replaces or masks sensitive personal data, for example, email, birthday, or social security number, reducing the risk of accidentally disclosing Personally Identifiable Information (PII). You can specify the properties to be masked or replaced and define the masking logic in the code.

The following transformation masks a social security number with zeros:

export function transformEvent(event, metadata) {
  if (event.context?.traits?.ssn) event.context.traits.ssn = "000-00-000"; // Change property
  return event;
}

Hash PII

This transformation hashes any sensitive user information like their email, social security number, etc., using SHA256 encryption.

The transformation hashing the user’s email is shown below:

import { sha256 } from "@rs/hash/v1";

export function transformEvent(event, metadata) {
  const email = event.context?.traits?.email;
  if (email) event.context.traits.email = sha256(email);
  return event;
}

Templates for data management, enrichment, and quality enforcement

Allowlist

This transformation allows events to reach a downstream destination only if a specific property contains certain values.

Some examples of how you can use this template are:

  • Allow only certain event names, like Product Added or Order Completed.
  • Send certain event types to a particular destination, like identify or track.
  • Send only the events that have a tracking plan linked to the source.

The allowlist transformation is shown below:

export function transformEvent(event, metadata) {
  const property = event.event; // Edit property; here it is event name
  const allowlist = ["<VALUE>", "<OTHER_VALUE>"]; // Edit allowlist contents
  if (!property || !allowlist.includes(property)) return;
  return event;
}

Denylist

This transformation blocks the events from reaching a downstream destination if a specific property contains certain values. For example, you can block all Product Added and Order Completed events or block certain event types (identify, track, etc.).

The denylist transformation is shown below:

export function transformEvent(event, metadata) {
  const property = event.event; // Edit property, here it is event name
  const denylist = ["<VALUE>", "<OTHER_VALUE>"]; // Edit denylist contents
  if (property && denylist.includes(property)) return;
  return event;
}

Geolocation Enrichment

This transformation enriches events with the geolocation data using an IP-to-geolocation API. This lets you easily query your events based on the geolocation data, for example, country or city.

The transformation is shown below:

export async function transformEvent(event, metadata) {
  if (event.request_ip) {
    try {
      const res = await fetchV2("<YOUR_API_ENDPOINT>" + event.request_ip); // Use your paid IP-to-geolocation API endpoint.
      event.context.geolocation = res.body;
    } catch {}
  }
  return event;
}

Parse User Agent

This transformation lets you add the user’s browser, engine, OS, device, and CPU-related information to the events. Adding this user metadata to your user events is helpful when you want to perform downstream actions later, for example, filter events coming from mobile devices.

info
This template uses the standard RudderStack library User Agent Parser which you can use for your custom transformations.

The transformation is shown below:

import { UAParser } from "@rs/userAgentParser/v1";

export function transformEvent(event, metadata) {
  const userAgent = event.context?.userAgent;
  if (userAgent) {
    const parser = new UAParser();
    const parsedUserAgent = parser.setUA(userAgent).getResult();
    event.context.parsedUserAgent = parsedUserAgent;
  }
  return event;
}

Event Sampling

This transformation sends only a subset of events to a downstream destination. You can anonymize the events and select a random subset from the anonymous events; this allows you to work with a small, manageable amount of data in the destination.

The event sampling transformation is shown below:

import { cyrb53 } from "@rs/hash/v1";

export function transformEvent(event, metadata) {
  const userId = event.userId;
  if (userId && parseInt(cyrb53(userId)) % 10 < 5) return;
  return event;
}

Dynamic Headers

This transformation sets the HTTP headers for your webhook destinations dynamically. It lets you set the headers based on the values in your data.

The transformation is shown below:

export function transformEvent(event, metadata) {
  event.header = {
    Authorization: "Basic <credentials>", // Change headers and values
    header_2: "value"
  };
  return event;
}

Dynamic Path

This transformation dynamically appends to the URL specified in your webhook destination configuration. This lets you send events to different paths based on the values in your event data. For example, you can send identify events to only to the /users URL path and the group events only to /organizations.

The following transformation appends a /search?email=${email} path to the webhook URL based on the email property present in the event:

export function transformEvent(event, metadata) {
  const email = event.context?.traits?.email; // Change property
  if (email) event.appendPath = `/search?email=${email}`; // Change property and appendPath
  return event;
}

Remove Null Properties

This transformation removes all event properties with null values; this is helpful when you want to reduce the number of unnecessary fields generated in downstream destinations.

The transformation is shown below:

export function transformEvent(event) {
  if (event.properties) {
    const keys = Object.keys(event.properties);
    if (keys) {
      keys.forEach(key => {
        if (event.properties[key] === null) delete event.properties[key];
      });
    }
  }
  return event;
}

User Enrichment

This transformation enriches the events by fetching user data like location, employment, or social media details using the Clearbit API and their email address. It is helpful when sending events with additional user metadata to various downstream destinations.

The transformation is shown below:

export async function transformEvent(event) {
  const email = event.context?.traits?.email;
  if (email) {
    const res = await fetch("<https://person.clearbit.com/v2/combined/find?email=>" + email, {
      headers: {
        "Authorization": "Bearer <your_clearbit_secure_key"
      }
    });
    event.context.traits.enrichmentInfo = res;
  }
  return event;
}

Rename properties

This transformation renames the properties to conform with the appropriate naming convention expected by the downstream destination, for example, first_name to firstName.

The transformation is shown below:

export function transformEvent(event, metadata) {
  const firstName = event.context?.traits?.first_name;
  if (firstName) {
    event.context.traits.firstName = firstName;
    delete event.context.traits.first_name;
  }
  return event;
}

Extract URL Parameters

This transformation lets you programmatically extract the query parameters from a URL. For example, in the URL rudderstack.com/transformations?publish=true, this transformation identifies the query parameter publish.

The transformation is shown below:

export function transformEvent(event, metadata) {
  const search = event.context?.page?.search;
  if (search) {
    event.context.page.parameters = {};
    search.substring(1).split("&").forEach(parameter => {
      const [key, value] = parameter.split("=");
      event.context.page.parameters[key] = value;
    });
  }
  return event;
}

Encryption

This transformation encrypts any Personally Identifiable Information (PII) including those stored in the cookies.

The transformation encrpyting the user’s email is shown below:

import { JSEncrypt } from "@rs/encrypt/v1";

const publicKey = `<RSA_PUBLIC_KEY>` // Add RSA public key

export function transformEvent(event, metadata) {
  const email = event.context?.traits?.email;
  if (email) {
    const crypt = new JSEncrypt();
    crypt.setKey(publicKey);
    event.context.traits.email = crypt.encrypt(email);
  }
  return event;
}

Decryption

This transformation decrypts the user’s Personally Identifiable Information (PII).

The transformation decrpyting the user’s email is shown below:

import { JSEncrypt } from "@rs/encrypt/v1";

const privateKey = `<RSA_PRIVATE_KEY>` // Add RSA private key

export function transformEvent(event, metadata) {
  const email = event.context?.traits?.email;
  if (email) {
    const crypt = new JSEncrypt();
    crypt.setKey(privateKey);
    event.context.traits.email = crypt.decrypt(email);
  }
  return event;
}

Clean Auth0 UserID

When using the Auth0 source to generate events from your website, the userId is prefixed with characters containing Auth0 followed by a pipe (|). This transformation removes any Auth0 userId prefixes.

A sample transformation is shown below:

export function transformEvent(event, metadata) {
    if(event.userId){
        const cleanedUserId = String(event.userId).split("|")[1];
        event.userId = cleanedUserId ? cleanedUserId : event.userId;
    }
    return event;
}

Questions? Contact us by email or on Slack