Runtime Functions in Transformations

Complete reference for runtime functions available in transformations.

This guide provides a complete reference for the runtime functions available in JavaScript and Python transformations.

announcement
Python transformations are available only in the RudderStack Growth and Enterprise plans.

Overview

RudderStack injects several runtime functions into your transformations. You can use these functions to:

metadata()

RudderStack injects the metadata function as the second argument to transformEvent and transformBatch. Use it to access event metadata and customize your transformation logic based on source, destination, or connection mode.

What you can do

  • Read source and destination identifiers for routing or filtering
  • Access the unique message ID for each event
  • Check the connection mode (deviceMode or cloudMode) in hybrid mode destinations
  • Access the device mode token (Custom-Authorization) for tokenization validation

What it returns

An object containing the following properties when available:

PropertyDescription
sourceIdThe source ID from the Settings tab of your source.
sourceNameThe source name set in the RudderStack dashboard. For example, JavaScript-QA, TestJSSource.
destinationIdThe destination ID from the Settings tab of your destination.
messageIdThe unique ID for each event.
sourceTypeThe source type, for example, Android, iOS.
destinationTypeThe destination type where RudderStack sends the transformed event, for example, Snowflake.
modeThe connection mode: deviceMode or cloudMode. Available for hybrid mode destinations.
Custom-AuthorizationThe device mode token when tokenization is enabled.

Examples

Usage

See Transform a single event for more information on using the metadata function.

fetch()

RudderStack injects an asynchronous fetch function in JavaScript transformations. Use it to make external API calls and enrich events with data from third-party services.

What you can do

  • Make HTTP requests (GET, POST, PUT, DELETE, and others) to external APIs
  • Enrich events with data from services like Clearbit, IP geolocation APIs, or custom backends
  • Pass custom headers and request bodies

What it returns

The response from the API call in JSON format.

warning

For JavaScript transformations, RudderStack imposes a 4 second execution timeout limit. This limit does not include the time for fetch or fetchV2 calls to complete. RudderStack recommends using batch API requests instead of a separate request per event when possible.

Depending on your use case, you may also need to allowlist RudderStack IP addresses for the API endpoints you access.

Examples

export async function transformEvent(event, metadata) {
  const res = await fetch("https://api.example.com/enrich", {
    method: "POST",
    headers: {
      "Content-Type": "application/json;charset=UTF-8",
      Authorization: "Bearer <authorization_token>"
    },
    body: JSON.stringify(event)
  });
  event.response = JSON.stringify(res);
  return event;
}

Usage

See the following sections for more information on using the fetch function:

fetchV2()

fetchV2 is a wrapper for the fetch call in JavaScript transformations. Use it when you need structured access to response properties such as status code, headers, and body, or when you need timeout control.

What you can do

  • Make external API calls with structured response handling
  • Access response status, URL, headers, and body separately
  • Set a timeout to handle slow or unresponsive APIs
  • Handle failures more efficiently than with raw fetch

What it returns

An object with the following properties:

PropertyDescription
statusThe HTTP status code of the response, for example, 200.
urlThe URL of the Fetch API request.
headersThe response headers.
bodyThe response body in JSON or TEXT format. By default, it is JSON.

Examples

export async function transformEvent(event, metadata) {
  try {
    const res = await fetchV2("https://api.example.com/data", { timeout: 1000 });
    if (res.status == 200) {
      event.response = JSON.stringify(res.body);
    }
  } catch (err) {
    log(err.message);
  }
  return event;
}

Using fetchV2 with credentials:

export async function transformEvent(event, metadata) {
  const url = getCredential('URL');
  const authToken = getCredential('authToken');
  const response = await fetchV2(`${url}/endpoint`, {
    headers: {
      Authorization: "Bearer " + authToken
    }
  });
  event.value = response.body;
  return event;
}
info
Depending on your use case, you may also need to allowlist RudderStack IP addresses for the API endpoints you access via fetchV2.

Usage

See the following sections for more information on using the fetchV2 function:

geolocation()

The geolocation function enriches events with geolocation data from an IP address. RudderStack uses the MaxMind GeoLite2 database embedded in its service.

info
This function is available only on the Growth and Enterprise plans. For source-level enrichment, RudderStack recommends the Geolocation Enrichment at Source feature.
announcement
If you host RudderStack on-premise, contact the Customer Success team to use this feature.

What you can do

  • Resolve an IP address to geolocation data
  • Enrich events with city, country, region, and timezone for analytics and segmentation
  • Query events by location in your warehouse or destination

What it returns

An object containing the following geolocation fields:

PropertyDescription
CityThe city name.
CountryThe country code.
RegionThe region or state.
LocationLatitude and longitude.
Postal codeThe postal or ZIP code.
TimezoneThe timezone.
warning
RudderStack returns a 400 Bad Request error if you pass a malformed IP address. The geolocation data varies in accuracy by country.

Examples

Usage

See Geolocation Enrichment for more information on using the geolocation function.

getCredential()

The getCredential function retrieves secrets and variables from the RudderStack credential store. Use it to avoid hardcoding sensitive data like API keys and tokens in your transformations.

info
The credential store and getCredential are available only on the Starter, Growth, and Enterprise plans.

What you can do

  • Retrieve secrets (encrypted) and variables (non-encrypted) from the credential store
  • Use API keys, tokens, and configuration values securely in transformations
  • Reference credentials by name without exposing them in transformation code

What it returns

  • Returns the credential value as a string when the key exists and is valid
  • Returns undefined (JavaScript) or null (Python) when the key does not exist or is invalid
warning
getCredential is a restricted keyword. Do not use it for naming functions or variables. You cannot use credentials in transformation libraries. RudderStack drops the event if an error occurs while using getCredential in a transformation connected to a destination.

Examples

Usage

See Transformation Credentials for more information on using the getCredential function.

log()

The log function captures output during transformation testing. Use it to inspect event data, metadata, or intermediate values when you run tests in the RudderStack dashboard.

What you can do

  • Debug transformations by printing values to the Logs section
  • Inspect event properties, metadata, or computed values during development
  • Trace execution flow when troubleshooting transformation logic

What it returns

Nothing. The function is used for its side effect of writing to the transformation logs.

info
You can pass a string, number, or object as an argument to the log function. Logs appear in the Logs section when you click Run Test in the transformation editor.

Examples

Usage

See Capture event information with logs for more information on using the log function.

See more

Questions? We're here to help.

Join the RudderStack Slack community or email us for support