# Custom Snowbridge script transformations
> Create custom JavaScript Snowbridge transformations to modify data, filter messages, set partition keys, and add HTTP headers.
> Source: https://docs.snowplow.io/docs/api-reference/snowbridge/configuration/transformations/custom-scripts/
> Documentation index: https://docs.snowplow.io/llms.txt

Custom transformation scripts may be defined in Javascript and provided to Snowbridge.

## The scripting interface

The script must define a main function with a single argument. Snowbridge will pass the `engineProtocol` data structure as the argument:

```go
type engineProtocol struct {
    FilterOut    bool
    PartitionKey string
    Data         interface{}
    HTTPHeaders  map[string]string
}
```

This structure is represented as an object in the script engine, and serves as both the input and output of the script.

Scripts must define a `main` function with a single input argument (JSDoc for type information is optional):

```js
/**
 * @typedef {object} EngineProtocol
 * @property {boolean} FilterOut
 * @property {string} PartitionKey
 * @property {(string | Object.<string, ?>)} Data
 * @property {Object.<string, string>} HTTPHeaders
 */

/**
 * @param {EngineProtocol} input
 * @return {Partial<EngineProtocol>}
 */
function main(input) {
    return input
}
```

## Accessing data

Scripts can access the message Data at `input.Data`, and can return modified data by returning it in the `Data` field of the output. Likewise for the partition key to be used for the destination - `input.PartitionKey` and the `PartitionKey` field of the output.

By default, the input's `Data` field will be a string in [enriched TSV format](/docs/destinations/custom-streaming/enriched-tsv-format/). This can be changed with the [SpEnrichedToJson](/docs/api-reference/snowbridge/configuration/transformations/builtin/spEnrichedToJson/) transform, or the Javascript transformation itself has a `snowplow_mode` option, which transforms the data to an object first.

The output of the script must be an object which maps to engineProtocol.

### `snowplow_mode`

`snowplow_mode` uses the [Go Analytics SDK](/docs/api-reference/analytics-sdk/analytics-sdk-go/) to parse the TSV fields into an object suitable for working with in Go. The result of the [`ParsedEvent.ToMap()`](https://pkg.go.dev/github.com/snowplow/snowplow-golang-analytics-sdk/analytics#ParsedEvent.ToMap) method is the input to your transform function.

The [keys of the resulting map](https://github.com/snowplow/snowplow-golang-analytics-sdk/blob/a3430fbe576483d615b713120cfb5e443897d572/analytics/mappings.go#L153) are defined by the Analytics SDK. Values are primitives (string, number, boolean) or, for timestamps (e.g. `derived_tstamp`, `collector_tstamp`), [`time.Time`](https://pkg.go.dev/time#Time) objects.

> **Tip:** To work with native Javascript [Date](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) objects for timestamps, construct one via `new Date(ts.UnixMilli())` where `ts` is a `time.Time` instance.
>
> When returned as part of `Data`, `time.Time` instances will [serialize in JSON](https://pkg.go.dev/time#Time.MarshalJSON) as [RFC3339](https://www.rfc-editor.org/rfc/rfc3339.html) strings.

Structured data ([self-describing event](/docs/fundamentals/events/#self-describing-events) payloads and [entities](/docs/fundamentals/entities/)) will have keys with a prefix of `unstruct_event_` or `contexts_`, the vendor name converted to snake case, the event/entity name in snake case, and the [schema model version](/docs/fundamentals/schemas/versioning/). For example:

| **Schema URI**                                                  | **Type** | **Key**                                              |
| --------------------------------------------------------------- | -------- | ---------------------------------------------------- |
| `iglu:com.snowplowanalytics.snowplow/web_page/jsonschema/1-0-0` | Entity   | `contexts_com_snowplowanalytics_snowplow_web_page_1` |
| `iglu:org.w3/PerformanceNavigationTiming/jsonschema/1-0-0`      | Entity   | `contexts_org_w3_performance_navigation_timing_1`    |
| `iglu:com.urbanairship.connect/OPEN/jsonschema/1-0-0`           | Event    | `unstruct_event_com_urbanairship_connect_open_1`     |

Timestamps in structured data values will always have their primitive representation (string/number) and not be `time.Time` instances.

## Transforming Data

For all the below examples, the input is a string representation of the below JSON object. For Snowplow data, using `snowplow_mode` will produce a JSON object input - see [the snowplow example](/docs/api-reference/snowbridge/configuration/transformations/custom-scripts/examples/).

```json
{
  "name": "Bruce",
  "id": "b47m4n",
  "batmobileCount": 1
}
```

To modify the message data, return an object which conforms to EngineProtocol, with the `Data` field set to the modified data. The `Data` field may be returned as either a string, or an object.

```js
loading...
```

[View on GitHub](<&#xA;https://github.com/snowplow/snowbridge/blob/v6.3.0/assets/docs/configuration/transformations/custom-scripts/create-a-script-modify-example.js&#xA;>)

## Filtering

If the `FilterOut` field of the output is returned as `true`, the message will be acknowledged immediately and won't be sent to the target. This will be the behavior regardless of what is returned to the other fields in the protocol.

```js
loading...
```

[View on GitHub](<&#xA;https://github.com/snowplow/snowbridge/blob/v6.3.0/assets/docs/configuration/transformations/custom-scripts/create-a-script-filter-example.js&#xA;>)

## Setting the Partition Key

To set the Partition Key in the message, you can simply set the input's PartitionKey field, and return it:

```js
loading...
```

[View on GitHub](<&#xA;https://github.com/snowplow/snowbridge/blob/v6.3.0/assets/docs/configuration/transformations/custom-scripts/create-a-script-setpk-example.js&#xA;>)

Or, if modifying the data as well, return the modified data and PartitionKey field:

```js
loading...
```

[View on GitHub](<&#xA;https://github.com/snowplow/snowbridge/blob/v6.3.0/assets/docs/configuration/transformations/custom-scripts/create-a-script-setpk-modify-example.js&#xA;>)

## Setting an HTTP header

For the `http` target only, you can specify a set of HTTP headers, which will be appended to the configured headers for the `http` target. Do so by providing an object in the `HTTPHeaders` field:

```js
loading...
```

[View on GitHub](<&#xA;https://github.com/snowplow/snowbridge/blob/v6.3.0/assets/docs/configuration/transformations/custom-scripts/create-a-script-header-example.js&#xA;>)

The headers will only be included if the target has the [`dynamic_headers = true` setting](/docs/api-reference/snowbridge/configuration/targets/http/#configuration-options) configured.

## Helper functions

- `hash(input, algorithm)` hashes the input value, returning the hex-encoded digest. Salt is configured using the `hash_salt_secret` parameter in the hcl configuration. Where a salt is provided, the result is an HMAC of the input keyed with the salt; where no value is provided, this function performs an unsalted hash of the input.

The following hash algorithms are supported:

- `sha1` - SHA-1 hash (160 bits)
- `sha256` - SHA-256 hash (256 bits)
- `md5` - MD5 hash (128 bits)

```js
hash(input.Data["app_id"], "sha1")
```

> **Warning: hash output changes in version 6.0.0**
>
> Version 6.0.0 changes the values this function returns. Before 6.0.0 it returned a PBKDF2-derived key rather than the digest, so hashes produced by 6.x do not match those produced by earlier versions for the same input. See the [6.x upgrade guide](/docs/api-reference/snowbridge/upgrade-guides/upgrade-guide-6-X-X/) for details.

- `allContexts(data, contextName)` returns an array of all entity instances for a given entity name across all schema versions present in the data object. Instances are ordered by schema version descending (highest version first). `contextName` is the snake\_case vendor and name portion of the key, without the `contexts_` prefix and version suffix. Returns an empty array if no matching keys are found.

> **Note:** `data` must be a parsed object, not a raw string. Use this function with `snowplow_mode`, or after parsing the data with `JSON.parse()`.

1. Access a field from the first entity instance:

```js
// input.Data: {"contexts_nl_basjes_yauaa_context_1":[{"agentName":"python-requests",...}]}

function main(x) {
  const data = JSON.parse(x.Data);
  x.Data = allContexts(data, "nl_basjes_yauaa_context")[0].agentName;
  // returns "python-requests"
  return x;
}
```

2. When multiple schema versions of the same entity are present, concatenate `label` values, with the highest version first:

```js
// input.Data: {"contexts_com_example_1":[{"label":"v1"}],"contexts_com_example_2":[{"label":"v2"}]}

function main(x) {
  const data = JSON.parse(x.Data);
  x.Data = allContexts(data, "com_example").map(c => c.label).join(",");
  // returns "v2,v1"
  return x;
}
```

3. When no matching entity is found, the function returns an empty array — use an optional chain to avoid errors:

```js
// input.Data: {"contexts_com_other_1":[{"url":"https://example.com"}]}

function main(x) {
  const data = JSON.parse(x.Data);
  const instances = allContexts(data, "com_example");
  x.Data = instances[0]?.url ?? "not_found";
  // returns "not_found"
  return x;
}
```

- `allUnstruct(data, eventName)` returns the payload object for a self-describing event matching the given event name. `eventName` is the snake\_case vendor and name portion of the key, without the `unstruct_event_` prefix and version suffix. Returns `undefined` if no matching key is found.

> **Note:** `data` must be a parsed object, not a raw string. Use this function with `snowplow_mode`, or after parsing the data with `JSON.parse()`.

1. Access a field from the event payload:

```js
// input.Data: {"unstruct_event_com_snowplowanalytics_snowplow_add_to_cart_1":{"sku":"item41",...}}

function main(x) {
  const data = JSON.parse(x.Data);
  x.Data = allUnstruct(data, "com_snowplowanalytics_snowplow_add_to_cart").sku;
  // returns "item41"
  return x;
}
```

2. When no matching event is found, the function returns `undefined` — use the nullish coalescing operator (`??`) to provide a fallback:

```js
// input.Data: {"unstruct_event_com_other_1":{"sku":"item1"}}

function main(x) {
  const data = JSON.parse(x.Data);
  x.Data = allUnstruct(data, "com_example") ?? "not_found";
  // returns "not_found"
  return x;
}
```

- `parseTimestamp(timestampStr, layout)` parses a timestamp string into a JavaScript `Date`. The `layout` argument is optional and defaults to `2006-01-02 15:04:05.999`, the format used by Snowplow enriched event timestamp fields such as `collector_tstamp`. To parse a different format, pass a `layout` using [Go reference time syntax](https://pkg.go.dev/time#pkg-constants), where each component of the reference time `Mon Jan 2 15:04:05 MST 2006` stands for that part of the timestamp. The function throws a `RangeError` if the input does not match the layout.

1. Parse a Snowplow timestamp using the default layout:

```js
// input.Data: {"collector_tstamp":"2026-06-15 09:30:00.000"}

function main(x) {
  const data = JSON.parse(x.Data);
  const ts = parseTimestamp(data.collector_tstamp);
  x.Data = ts.toISOString();
  // returns "2026-06-15T09:30:00.000Z"
  return x;
}
```

2. Parse a custom format by passing a `layout`:

```js
// input.Data: {"event_time":"15/06/2026"}

function main(x) {
  const data = JSON.parse(x.Data);
  const ts = parseTimestamp(data.event_time, "02/01/2006");
  x.Data = ts.getUTCFullYear();
  // returns 2026
  return x;
}
```

## Configuration

Once your script is ready, you can configure it in the app by following the [Javascript](/docs/api-reference/snowbridge/configuration/transformations/custom-scripts/javascript-configuration/) configuration page.

You can also find some complete example use cases in [the examples section](/docs/api-reference/snowbridge/configuration/transformations/custom-scripts/examples/).
