You will learn

Learn about Code, and how to create custom functions that are executed directly by Klaviyo.

Code requires custom development and Klaviyo’s support team is unable to offer hands-on assistance. If you don't have a developer on your team and are not comfortable writing code yourself, consider reaching out to a Klaviyo Partner for assistance.

Before you begin

Advanced KDP is not included in Klaviyo’s standard marketing application, and a subscription is required to access the associated functionality. Head to our billing guide to learn how to purchase this plan.

What is Code?

Code enables you to execute custom functions in response to events captured in Klaviyo. You can write your own JavaScript or Python functions in the Code editor, and they are then executed directly in the platform.

With Code, you can send data to your external systems without having to set up a public HTTP endpoint to receive webhooks, and build custom functionality that is triggered in response to an event’s occurrence. You can also access many popular prebuilt modules to facilitate creating custom solutions.

Topics

With the exceptions below, Code allows you to execute custom functions in response to events that can be queried for via the Get Events API.

These include:

  • Email events (e.g., Clicked email, Marked email as spam)
  • SMS events (e.g., Sent SMS, Received SMS)
  • Push notification events (e.g., Received push, Bounced push)
  • Events from integrations (i.e., events from first-party integrations created by Klaviyo)
  • API events (i.e., events synced through Klaviyo’s APIs)

Klaviyo Code does not support the following events as topics:

  1. Email opened
  2. Email received

Granting permissions

When you first access Code, you’re prompted to authorize the Code OAuth application. This lets your Code functions access data in your Klaviyo account.

After you grant access, you return to Code. If a setup confirmation appears, click Dismiss to continue.

Create a function

  1. Navigate to Data management > Code.
  2. Click Get started if you haven’t created a function yet, or Create function if you already have functions.
Create a function button
Create a function button
  1. On the Recipes page, choose a prebuilt recipe, Blank Python Function, or Blank Node.js Function.
image (9).jpg
image (9).jpg
  1. If you choose a prebuilt recipe, review its code and instructions, then click Select to continue.
image (10).jpg
image (10).jpg
  1. In the Details step, configure your function:
    • Name your function
      A name to identify your function.
    • Select a Trigger
      The event that will trigger your code’s execution.
    • Review the Runtime
      The runtime is set automatically by the blank function or recipe you selected: Python or Node.js.
3.11.jpg
3.11.jpg
  1. Click Create function. The function opens with the following tabs:
  • Editor
  • Test
  • Logs

Editor

On the Editor page in Code, you’ll see the page split into 3 tabs:

  • Code
    The code tab has an editor where you can write Python or JavaScript functions.
  • Modules
    Modules are 3rd party packages that add functionality to your functions.
  • Environment Variables
    Environment variables are the key-value pairs that your function accesses when it runs.

Code

On the Code tab, you’ll see an editor you can use to write Python or JavaScript functions that are executed in response to the selected topic.

3.11(2).jpg
3.11(2).jpg
js.jpg
js.jpg

Handler function parameters

Keep the entry-point structure provided by your blank function or recipe. In Python, use a function named handler. In JavaScript, use a default-exported function. Both accept 2 parameters:

  • Event
    Contains the triggering event’s data in JSON:API format. For custom actions in flows with a non-event trigger (e.g., Added to List), this parameter is None in Python or null in JavaScript.
  • Context
    Contains additional metadata about the function execution, including the profile associated with the function invocation. You can access the profile object via context.profile in JavaScript or context["profile"] in Python.

Below are examples of the event and context parameters that are passed to the handler function.

Example event format

json
{
  "data": {
    "type": "event",
    "id": "7S2q9haejYG",
    "attributes": {
      "timestamp": 1694435729,
      "event_properties": {
        "MfaEnabled": false,
        "IpAddress": "000.00.0.0",
        "UserAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36",
        "UserRole": "Owner",
        "SessionId": "34sh0a9nh8ngnk2nfacjxmt592yx40ib",
        "LoginType": "Username_password",
        "current_company_id": "XXXXX",
        "$event_id": "1694435729"
      },
      "datetime": "2023-09-11 12:35:29+00:00",
      "uuid": "b0b8fe80-509f-11ee-8001-278cc529fcd3"
    },
    "relationships": {
      "profile": {
        "data": {
          "type": "profile",
          "id": "123456"
        },
        "links": {
          "self": "https://a.klaviyo.com/api/events/7S2q9haejYG/relationships/profile/",
          "related": "https://a.klaviyo.com/api/events/7S2q9haejYG/profile/"
        }
      },
      "metric": {
        "data": {
          "type": "metric",
          "id": "4Tdup6"
        },
        "links": {
          "self": "https://a.klaviyo.com/api/events/7S2q9haejYG/relationships/metric/",
          "related": "https://a.klaviyo.com/api/events/7S2q9haejYG/metric/"
        }
      }
    },
    "links": {
      "self": "https://a.klaviyo.com/api/events/7S2q9haejYG/"
    }
  }
}

Example context format

json
{
    "company_id": "XXXXX",
    "trigger": {"type": "event", "uid": "123456"},
    "function_id": "123456"
}

Modules

On the Modules tab, you can select from the most popular prebuilt modules (i.e., 3rd-party packages that add capabilities to your functions).

  1. On the Modules tab, click Add module. If modules are already installed, click Add new module.
Add module button
Add module button
  1. Search for the module. Select a version if a version dropdown is available, then click Add.
Add module modal
Add module modal

Once added, you can use the module with the code you write in Klaviyo.

You should refer to the external module’s native documentation for information regarding how to use it.

Added modules
Added modules
The klaviyo module

All Code functions come with a custom klaviyo package that is pre-installed into your Code environment. This module allows your functions to access the data in your Klaviyo account without needing to supply any credentials, such as an API key.

The API of the klaviyo module depends on whether your code is written in Python or JavaScript.

Python klaviyo module

The API of the pre-installed klaviyo module is the same as the Klaviyo SDK object you would normally instantiate with the klaviyo-api Python module. You can think of the klaviyo module as a pre-instantiated klaviyo SDK client.

For example, in a traditional workflow you would first instantiate a new Klaviyo SDK client by passing an API key to the constructor, and then use the resulting SDK object.

python
from klaviyo_api import KlaviyoAPI
import os

def handler(event, context):
    klaviyo = KlaviyoAPI(api_key=os.getenv("KLAVIYO_API_KEY"))
    print(klaviyo.Metrics.get_metrics())

With Code, you just need to import the klaviyo object and authentication is handled for you.

python
import klaviyo

def handler(event, context):
    print(klaviyo.Metrics.get_metrics())

View the available Klaviyo objects and their methods.

JavaScript klaviyo module

When using the pre-installed klaviyo module in your JavaScript functions, import the specific Klaviyo features you want to access using curly brace syntax from the klaviyo module. Then use them as you normally would an API object using the klaviyo-api JavaScript module.

javascript
import { Metrics } from 'klaviyo';

export default async (event, context) => {
  console.log(await Metrics.getMetrics());
};

View the available Klaviyo objects and their methods.

Environment variables

The Environment variables tab allows you to set key-value pairs that your code in Klaviyo can reference when it runs. These can be used to store information like credentials and secret keys so your functions can access them as they run.

  1. On the Environment Variables tab, click Add a variable.
Add environment variables button
Add environment variables button
  1. Enter the variable’s Key and Value, then click Save.
Key-value pairs set for environment variable
Key-value pairs set for environment variable

Once created, the environment variables will be listed on the page and can be used in your code.

In Python, import os, then use os.getenv("KEY"). In Node.js, use process.env.KEY. Replace KEY with your variable’s exact key.

Created environment variables
Created environment variables

To update an existing variable, open its row menu and select Edit. Change the Value, then click Save.

Test

The Test tab lets you run your function with recent events and review its logs and errors.

To test your function:

  1. Open the Test tab and click Run test. If an event is already selected, click Change event to choose another.
Run test button
Run test button
  1. Select an event to run the test. You can choose from up to 10 recent events for the function’s trigger from the past 30 days.
Recent events to test with
Recent events to test with
  1. Review the logs and any errors in the Test output panel.
Test output
Test output

To run the function again with the same event, click Test at the top of the editor. To use a different event, click Change event.

Logs

The Logs tab shows the health of your ongoing Code functions. You’ll see:

  • Status
    Whether an execution completed or failed.
  • Execution Time
    The time the function took to run, in milliseconds.
  • Date
    A timestamp for when the function was executed.

Click a Run ID to see its logs. Click View all details for more information about that execution.

Execution limits

Klaviyo Code has the following execution limits:

  • Function timeout
    Functions in Code can execute for up to 15 seconds before they time out.
  • Function rate limit
    Functions in Code allow for up to 25 concurrent executions per function.

Deploying code

After testing your function, select Live from the status dropdown to deploy it.

Toggle to deploy code
Toggle to deploy code

If deployment fails, review the error in the Editor tab, correct the code, and try again.

Once set to live, the code you write will execute each time the topic event is captured in Klaviyo.

When a function is set live, there may be up to a 15 minute delay before events begin to trigger the function.

Example solution

Below is an example of a custom solution being implemented with Code.

In this example, a Booked shoot custom event is captured when a customer books a shoot with the brand. The function reads the event’s booking_city and booking_postcard_url properties and stores them together on the customer’s profile for use in targeted emails and segmentation.

The Recent bookings profile property stores a list of bookings processed by the function. Set the limit to 5 to keep the 5 most recently processed bookings, which you can loop through in an email template.

Code

The Python code for this solution is written in the Code editor and is executed directly by Klaviyo.

Code_updates.jpg
Code_updates.jpg

Example code

python
import os
import klaviyo

def handler(event, context):
    max_properties = int(os.getenv("MAX_PROPERTIES_TO_STORE"))
    profile_id = event["data"]["relationships"]["profile"]["data"]["id"]
    booking_city = event["data"]["attributes"]["event_properties"]["booking_city"]
    booking_postcard_url = event["data"]["attributes"]["event_properties"]["booking_postcard_url"]

    profile = klaviyo.Profiles.get_profiles(filter=f'equals(id,"{profile_id}")')
    current_bookings = profile["data"][0]["attributes"]["properties"].get("Recent bookings", [])

    current_booking = {
        "booking_city": booking_city,
        "booking_postcard_url": booking_postcard_url
    }
    current_bookings.insert(0, current_booking)
    profile_properties = {
      "data": {
        "type": "profile",
        "id": profile_id,
        "attributes": {
          "properties": {"Recent bookings": current_bookings[0:max_properties]}
        }
      }
    }

    klaviyo.Profiles.update_profile(profile_id, profile_properties)

Modules

In this example, the built-in klaviyo module is used. The klaviyo module relies on the klaviyo-api module being added to the function. Once added, the klaviyo module will handle authentication for you, so no API key is needed.

Environment variables

Environment variables can be used to store information like credentials and secret keys so your functions can access them as they run. For this example, the following key-value pair is set:

  • MAX_PROPERTIES_TO_STORE
    Set this environment variable’s Value to 5 to keep up to 5 bookings in Recent bookings. Click Save.

Testing

While creating the function to set event data as profile properties, the Test tab is used to verify the expected output.

test_output.jpg
test_output.jpg

Logs

After you test the function and set it to Live, the Logs tab shows the results of executions triggered by Booked shoot events.

Logs.jpg
Logs.jpg

Outcome

With this Code function in place, as customers sign up for shoots and trigger the custom Booked shoot event, the event data will be stored on the customer profile for use in segmentation and targeted campaigns.

Implementing Recipes

Recipes in Code allow you to implement prebuilt solutions without the need for custom development.

To implement a Recipe in your Klaviyo account:

  1. On the Code page, click Get started if this is your first function, or Create function if you already have functions.
  2. Choose the recipe you want to use. Review its code and instructions in the preview.
  3. Click the Select button to continue.
Currency converter recipe in Klaviyo
Currency converter recipe in Klaviyo
  1. Choose a name for the function and the trigger that will cause it to execute. The runtime is automatically set based on the code for the Recipe.
  2. Select the Create function button.
  3. Once the function has been created, set the relevant environment variables so the function has the data it needs to run.
  4. Test the function on the Test tab. After you confirm the expected result, select Live from the status dropdown.

Recipes may require you to update certain fields to match your desired naming preferences and the data in your events. See the instructions for the Recipe to view which fields can be renamed and edited.

Additional resources

  • Getting started with Advanced KDP

    Learn more about using Advanced KDP (Klaviyo data platform) to gather robust customer insights across all your marketing initiatives. Advanced KDP enables more advanced data management, manipulation, and analysis. It also provides actionable strategies to employ across each of your individual audiences and your business as a whole.

  • Understand the different webhooks available in Klaviyo

    Learn about the differences between webhook solutions available in Klaviyo, and when you should use each one.

Was this article helpful?
Use this form only for article feedback. Learn how to contact support.

Explore more from Klaviyo

Community
Connect with peers, partners, and Klaviyo experts to find inspiration, share insights, and get answers to all of your questions.
Partners
Hire a Klaviyo-certified expert to help you with a specific task, or for ongoing marketing management.
Support

Access support through your account.

Email support (free trial and paid accounts) Available 24/7

Chat/virtual assistance
Availability varies by location and plan type