Skip to main content
Sitecore Documentation
  • Learn
  • Downloads
  • Changelog
  • Roadmap
CDPCloud Portal
Sitecore CDP
  • Data browser
    • Ideas for audience activation
        • Data in the export
        • JavaScript in the export
        • The output of an export
        • Accessing the exported data
        • Sending exported data to a third-party system
        • Create a recipe in Sitecore Connect
        • Testing the export
        • Export statuses
    • Manage audience exports
    • Troubleshooting
  • Glossary
  1. Audience export
  1. Sitecore CDP
  2. Audience export
  3. JavaScript in the export

JavaScript in the export

When creating an audience export, you can use JavaScript to compute data in addition to what's already in the guest profile. This lets you enrich the data you export from Sitecore CDP.

For example, if the guest's date of birth is in the guest profile, you can include it in the output as ${guest.dateOfBirth}, without additional coding required. If the guest's age, however, isn't in the guest profile, you can compute it with JavaScript and then include it in the output.

To use JavaScript in an audience export, you can:

  • Enter functions in the JavaScript code editor. You can write the code manually, or generate it with the Code Assistant using natural language. See code snippets for example functions.

  • Call a utility function in a field on the Output structure tab.

Here's a video that introduces you to using JavaScript in audience exports:

Computing data using functions

You can use JavaScript functions in an audience export by clicking Output format > Define output > JavaScript code editor. Make sure that you put all the functions inside a single function and that you return a single object:

(function () {
  /* first function */
  /* second function */
  /* third function */
  return {} // return a single object
})()

In the JavaScript, you can work with data from the guest profile. As you start typing guest in the code editor, an autocomplete list of references to the guest data model appears:

Writing JavaScript and referencing data from the guest data model.
Note

To prevent errors, we recommend that you log messages to the test log using console.log(). You can add logs manually or prompt the Code Assistant to create them for you. You'll use the test log when you test the export.

Basic and Advanced mode

You can write JavaScript in Basic or Advanced mode. To select a mode, click Basic or Advanced at the top of the Define output screen.

Here's an overview of the differences between Basic and Advanced mode:

  • In Basic mode, the object that the JavaScript returns must be flat with no nesting allowed. The object keys can be strings, numbers, or Boolean values. After writing the function, you use the object key names to include the data in the output on the Output structure tab. The output can be JSON or CSV.

  • In Advanced mode, the object that the JavaScript returns can include strings, numbers, Boolean values, and other objects. This means that the object can be nested, allowing you to include more complex data in the output, such as guest.sessions. In Advanced mode, there is no need to manually include the computed data in the output. Instead, the JSON output will match the structure of the complete object that the JavaScript returns. CSV is not supported.

Examples

Basic mode
Example 1. Compute the guest's age

Here's an example JavaScript function in Basic mode. It computes the guest's approximate age by referencing their date of birth in the guest profile:

(function () {
    // Calculate age based on a date
    function getAge(date) {
    var today = new Date();
    var birthDate = new Date(date);
    var age = today.getFullYear() - birthDate.getFullYear();
    var m = today.getMonth() - birthDate.getMonth();
    if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
        age--;
    }
    return age;
    }
    
    // Calculate the guest's age based on their date of birth
    var guestAge = "";
    if (guest.dateOfBirth) {
        guestAge = getAge(guest.dateOfBirth);
    }
  
    // Return the guest's age in the "age" variable. Then, reference "age" as ${jsResult.age} on the Output structure tab.
    return { age: guestAge }
})()

After writing the function, make sure to Save your changes.

In the returned object, the key name is age. To include the guest's age in the output, write ${jsResult.age} in a column on the Output structure tab.



Advanced mode
Example 2. Return nested session data

Here's an example JavaScript function in Advanced mode. It returns the guest's session data from the previous 30 days. An audience export with this data helps you find and re-engage inactive guests:

(function() {
  load("classpath:moment.js");

  const sessionDataArray = [];
  const tenDaysAgo = moment.utc().subtract(30, "days").format("YYYY-MM-DD");

  if (guest.sessions && guest.sessions.length > 0) {
    for (let index in guest.sessions) {
      const session = guest.sessions[index];
      const sessionDate = moment(session.startedAt).format("YYYY-MM-DD");

      if (sessionDate >= tenDaysAgo) {
        console.log(`Processing session dated: ${sessionDate}`);
        sessionDataArray.push({
          "browserRef": session.browserRef || "",
          "cartType": session.cartType || "",
          "channel": session.channel || "",
          "pointOfSale": session.pointOfSale || "",
          "duration": session.duration || 0,
          "value": session.value || 0,
          "events": session.events || []
        });
        console.log("Session data added");
      }
    }
  }
  console.log("All session data processed.");
  return {
    "sessions": sessionDataArray
  };
})()

After writing the function, make sure to Save your changes. Then, test the audience export to verify that the JavaScript computation is successful.



Including the computed data in the output

If you write JavaScript in Basic mode, you need to include the computed data on the Output structure tab, in the Attribute value field of a string or number field.

When referencing a key from the object that the JavaScript returns, use the ${jsResult.objectKeyName} notation. For example, if the JavaScript contains the age attribute in the returned object, include that in the Attribute value field as ${jsResult.age}:

Including the computed data from the JavaScript in the output structure.

After updating the fields, make sure to Save your changes. Then, test the audience export to verify that the JavaScript computation is successful.

Calling utility functions

Utility functions help you access data in the guest profile and make data transformations. For example, you can join strings, transform dates, or hash sensitive data so it is securely exported.

You can call these functions in an audience export if you're in Basic mode on the Define output screen, by clicking Output structure > Add column, then entering the utility function in the Attribute value field of a string or number field. Make sure to replace the function parameters with values of your choice.

Here's an example of calling the ${sha256()} utility function to securely export a guest's email address:

Or consider a guest profile with the following data extension object:

{
  "dataExtensions": [
    {
      "name": "ext1",
      "values": {
        "MemberCardCategoryRenewalDate": "18/05/2026",
        "MemberCardBalance": 22000,
        "MemberCardType": "shop&miles",
        "MemberCardCategory": "premium",
        "MilesRequiredForMemberCardCategory": 3000
      }
    }
  ]
}

You can call ${getDataExtension(guest.dataExtensions, "ext1", "MemberCardCategory", "not-available")} in the Attribute value field to access the value for MemberCardCategory and include it in the output.

After updating the fields, make sure to Save your changes. Then, test the audience export to verify that the JavaScript computation is successful.

If you have suggestions for improving this article, let us know!

Documentation Assistant

This assistant uses AI to generate responses based on Sitecore documentation. While it has access to official sources, answers may be incomplete or inaccurate and should not be considered official advice or support.
Powered by
k
kapa.ai
Protected by reCAPTCHA

© Copyright 2026, Sitecore A/S or a Sitecore affiliated company.
All rights reserved.

Privacy policySitecore Trust CenterTerms of use