# Transformation Libraries


RudderStack's transformation libraries feature lets you reuse the same code in multiple transformations.

{{<badge label="Node.js Version" message="18.x" color="7447fc" link="https://github.com/rudderlabs/rudder-transformer/blob/main/.nvmrc" >}} {{<badge label="Python Version" message="3.11" color="7447fc" >}}

## Required permissions

- [Admins]({{< ref "access-management/member-management.md#member-roles" >}}) have full access to manage transformation libraries.
- [Members]({{< ref "access-management/member-management.md#member-roles" >}}) must have the [**Transformation Libraries**]({{< ref "access-management/policies-overview.md#resource-permissions" >}}) permission in their workspace policy.

{{< details "**Click here to see how these permissions appear in the workspace policy**." >}}
<br />

{{< figure src="images/access-management/transformation-libraries.webp" alt="Permissions to manage transformation libraries in RudderStack dashboard" >}}

{{< /details >}}
<br />

#### Permissions for legacy RBAC system

In the [legacy Permissions Management (RBAC) system]({{< ref "archive/dashboard-guides/user-management.md" >}}):

- [Org Admins]({{< ref "archive/dashboard-guides/user-management.md#organization-roles" >}}) can edit transformation libraries
- Members must have the **Grant edit access** permission in **Transformations and Library** toggled on to edit transformation libraries

{{< image src="images/access-management/permissions/legacy/transformations.webp" alt="Transformations permissions in the legacy framework" >}}

## Add transformation library

1. In the [RudderStack dashboard](https://app.rudderstack.com/), go to **Collect** > **Transformations** and click the **Libraries** tab. Then, click **Create Library**.

{{< image src="images/features/transformations/create-library.webp" alt="Adding a library" >}}

2. Add the library **Name**, **Description** and select the language to write the library function. You can also add multiple functions in a single library.

{{< info >}}
RudderStack supports Python libraries only in the RudderStack [Growth](https://rudderstack.com/pricing/) and [Enterprise](https://www.rudderstack.com/enterprise-quote/) plans.
{{< /info >}}

{{< warning >}}
JavaScript transformation libraries run in an isolated environment — no Node.js modules (like `fs`, `require`) or browser APIs (like `window`, `btoa`) are available. Only standard JavaScript features are supported.
{{< /warning >}}

{{< image src="images/features/transformations/add-new-library.webp" alt="Adding a library" >}}

3. Click **Run Test** to ensure the library code has the correct syntax. A **Test Passed** message pops up once the test runs successfully.

{{< image src="images/features/transformations/library-test-passed.webp" alt="Library test passed" >}}

## Use libraries in transformations

To use the libraries in your existing transformations, note the library name listed in the **Import library name** column in the RudderStack dashboard:

{{< image src="images/features/transformations/libraries-in-transformations.webp" alt="Using libraries in transformations" >}}

{{< info >}}
RudderStack converts the library name into **camel case without spaces**; this becomes your **library handle** which you can use across multiple transformations. For example, if your library name is `Sample Transformation Library`, then the library handle would be `sampleTransformationLibrary`.
{{< /info >}}

You can then use the library in a transformation with a simple `import` statement. Refer to the below use case for more information.

#### Use case

Suppose you want to filter the events that don't contain an email address with the RudderStack domain. To do so, you can import a `rudderEmail` function from the transformation library `isRudderEmail`.

The `rudderEmail` function containing the filtering logic is shown below:

{{< tabs tabTotal="2" >}}
{{% tab tabName="JavaScript" %}}
```javascript
export function rudderEmail(email) {
    return /@(rudderlabs|rudderstack)| \+ruddertest/.test(email);
}
```
{{% /tab %}}
{{% tab tabName="Python" %}}

```python
import re

def rudderEmail(email):
  match = re.search('@(rudderlabs|rudderstack)|\+ruddertest', email)
  if match:
    return True
  return False
```
{{% /tab %}}
{{< /tabs >}}

The following snippets demonstrate how you can import this function in a transformation:

{{< tabs tabTotal="2" >}}
{{% tab tabName="JavaScript" %}}
```javascript
import { rudderEmail } from "isRudderEmail";
export function transformEvent(event) {
  const email =
    event.context && event.context.traits && event.context.traits.email;
  if (email) {
    if (!rudderEmail(email)) return;
  }
  return event;
}
```
{{% /tab %}}
{{% tab tabName="Python" %}}

```python
from isRudderEmail import rudderEmail

def transformEvent(event, metadata):
    email = event.get("context", {}).get("traits", {}).get("email")
    if email:
        if not rudderEmail(email):
            return
    return event
```
{{% /tab %}}
{{< /tabs >}}

On clicking **Run Test**, a sample event not containing the RudderStack email domain is filtered out:

{{< image src="images/features/libraries-in-transformations-run-test.webp" alt="Filtering out events using libraries in transformation" >}}

## Import multiple functions from single library

The following snippets highlight how to **correctly** import functions from a library:

{{< tabs tabTotal="2" >}}
{{% tab tabName="JavaScript" %}}
```javascript
// ---------------
import { getLoss } from "getFinanceData";

// OR

import { getLoss, getRevenue, getProfit } from "getFinanceData";
import {
  getLoss,
  getRevenue,
  getProfit
} from "getFinanceData";

// For default getPrice import
import getPrice, { getRevenue, getProfit } from "getFinanceData";

// alias imports
import getPrice as gp, { getRevenue as gr, getProfit } from "getFinanceData";
// usage: gp(event), gr(event), getProfit(ev)

import * as GFD from "getFinanceData";
// usage: GFD.getRevenue(ev), GFD.getProfit(ev)
// for default import: GFD.default(ev)
```

{{% /tab %}}
{{% tab tabName="Python" %}}

```python
from getFinanceData import getRevenue, getProfit
// usage: getRevenue(event), getProfit(event)

from getFinanceData import getRevenue as gr, getProfit
// usage: gr(event), getProfit(ev)

import getFinanceData
// usage: getFinanceData.getRevenue(event), getFinanceData.getProfit(event)
```
{{% /tab %}}
{{< /tabs >}}

The following snippets highlight the **incorrect** way of importing the library functions:

{{< tabs tabTotal="2" >}}
{{% tab tabName="JavaScript" %}}
```javascript
// -----------------
import * from "getFinanceData";
getPrice(ev)

// OR

import getPrice as gp from "getFinanceData";
getPrice(ev)
```
{{% /tab %}}
{{% tab tabName="Python" %}}

```python
import getRevenue, getProfit from getFinanceData
import { getRevenue, getProfit } from getFinanceData

from getFinanceData import *
```
{{% /tab %}}
{{< /tabs >}}

## Delete library

{{< warning >}}
You cannot delete a library that is referenced or imported in a transformation.
{{< /warning >}}

To delete a library, go to **Collect** > **Transformations** > **Libraries** and click the **Delete** button next to the library that you want to delete.

## Default RudderStack libraries

RudderStack provides some default libraries that you can import in your transformations for implementing various use cases like encrypting, decrypting, or hashing PII, parsing user agent, and using the localized version of Apple's device mode information in your events.

See the [GitHub codebase](https://github.com/rudderlabs/rudder-libraries) for the code and implementation-specific details for these libraries.

{{< warning >}}
Currently, these predefined RudderStack libraries are available only for JavaScript.
{{< /warning >}}

Use the following structure to import the RudderStack libraries:

```javascript
@rs/<libraryname>/v1
```

A sample import statement is shown below:

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

The following table lists the default RudderStack libraries and their usage:

| RudderStack library name | Usage |
| :----| :----|
| `encrypt` | Used in the [Encryption]({{< ref "transformations/templates.md#encryption" >}}) / [Decryption]({{< ref "transformations/templates.md#decryption" >}}) transformation template.<br /><br />Lets you encrypt or decrypt PII, including PII stored in cookies. |
| `hash` | Used in the [Hash PII]({{< ref "transformations/templates.md#hash-pii" >}}) transformation template.<br /><br />Hides sensitive PII like the user's email, birthday, social security number, etc. You can use either **MD5**, **SHA256**, or **cyrb53** to hash your PII. |
| `userAgentParser` | Used in the [Parse User Agent]({{< ref "transformations/templates.md#parse-user-agent" >}})  transformation template. <br /><br />Adds the user's browser, engine, OS, device, and CPU-related information to the events. |
| `localizeAppleDeviceModel` | Used in the [Localize Apple Device Model]({{< ref "transformations/templates.md#localize-apple-device-model" >}})  transformation template. <br /><br />Lets you use the localized version of Apple's device model information present in your event's `context.device.model`. | 

## FAQ

#### How can I use a npm package not provided by RudderStack in my transformations?

To use a different library (other than the [default libraries](#default-rudderstack-libraries) provided by RudderStack) in your transformations:

1. Add a pure vanilla script as a [transformation library](#add-transformation-library).

{{< warning >}}
All the imports and functions referenced in the code must have their implementation in the same file — essentially, a self-sufficient minified JavaScript implementation of the required package.
{{< /warning >}}

2. [Import the library](#use-libraries-in-transformations) in your transformation.

##### **Example**

Suppose you want to use the [blueimp/JavaScript-MD5](https://github.com/blueimp/JavaScript-MD5/blob/master/js/md5.min.js) library to hash your PII.

1. Your [MD5 function](https://github.com/blueimp/JavaScript-MD5/blob/master/js/md5.min.js) looks as follows:

```javascript
! function(n) {"use strict";function d(n, t) {var r = (65535 & n) + (65535 & t);return (n >> 16) + (t >> 16) + (r >> 16) << 16 | 65535 & r} ... ... module.exports = t : n.md5 = t}(this);
```

{{< warning >}}
For this example, note that:

- The `min.js` file is readily available — hence no other action is required. Otherwise, you will need to write a `.js` file separately.
- The method used as the entry point method is `md5` and it uses the MD5 (hexadecimal), MD5 (raw), HMAC-MD5 (hexadecimal), and HMAC-MD5 (raw) functions —  make sure to include these function implementations in the file.

  - The above functions may also reference other methods — make sure to include their implementations in the file, and so on.
- Include only minimal and relevant code in the file to avoid performance issues.
{{< /warning >}}

2. Add the above code in a [new transformation library](#add-transformation-library), for example, `md5Library`.
3. Import the above library in your transformation to hash sensitive PII:

```javascript
// Import the MD5 function from your library
// Assuming the library handle is 'md5Library'

import { md5 } from "md5Library";

export function transformEvent(event) {
  // Get email from event properties
  const email = event.properties?.email;
  
  if (email) {
    // Hash the email using MD5
    event.properties.email = md5(email);
  }
  
  return event;
}
```

This transformation will hash any email address in the event properties using the provided MD5 algorithm.
