---
title: "Getting started with Code"
description: "Learn about Code, and how to create custom functions that are executed directly by Klaviyo."
canonical_url: "https://help.klaviyo.com/hc/en-us/articles/18620644491035"
markdown_url: "https://help.klaviyo.com/hc/en-us/articles/18620644491035.md"
locale: "en-us"
category: "Advanced KDP & Personalization"
section: "Code"
updated: "2026-10-26"
---

# Getting started with Code

## 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

**📝 Note:** [Advanced KDP](https://help.klaviyo.com/hc/en-us/articles/17655007276059.md) is not included in Klaviyo’s standard marketing application, and a subscription is required to access the associated functionality. Head to our [billing guide](https://help.klaviyo.com/hc/en-us/articles/115000976672.md) 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.

**📝 Note:** Learn [how to build custom functions using Code](https://academy.klaviyo.com/build-custom-functions-with-code).

## 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](https://developers.klaviyo.com/en/reference/get_events).

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)



**📝 Note:** 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](https://cdn.sanity.io/images/6ct6b26e/help-center-prod/eadf1a4261912a5b8e63a085d204707f622eb20a-2506x692.jpg?auto=format)

3. On the **Recipes** page, choose a prebuilt recipe, **Blank Python Function**, or **Blank Node.js Function**.



![image (9).jpg](https://cdn.sanity.io/images/6ct6b26e/help-center-prod/3a07019441694f3983f0125b673d10cd08b79b20-3030x1682.jpg?auto=format)

4. If you choose a prebuilt recipe, review its code and instructions, then click **Select** to continue.



![image (10).jpg](https://cdn.sanity.io/images/6ct6b26e/help-center-prod/471e76a04525d4d1ed1ae103659fb777c6bbe0a8-3446x1780.jpg?auto=format)

5. 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](https://cdn.sanity.io/images/6ct6b26e/help-center-prod/6d4a6e3bd8394d23572b64ef3039e9a451da34dd-2342x834.jpg?auto=format)

6. 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](https://cdn.sanity.io/images/6ct6b26e/help-center-prod/2282315e7c23ce218a2da456932ab22bf4ede1d7-2120x1232.jpg?auto=format)

![js.jpg](https://cdn.sanity.io/images/6ct6b26e/help-center-prod/f22d2e77e41d24007c665279e015126dc28d3040-2112x1228.jpg?auto=format)

### 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](https://cdn.sanity.io/images/6ct6b26e/help-center-prod/c5d0711e07a66aa934e4fef47d3c5a3277eec5f6-2062x728.jpg?auto=format)

2. Search for the module. Select a version if a version dropdown is available, then click **Add**.



![Add module modal](https://cdn.sanity.io/images/6ct6b26e/help-center-prod/36c2e079a47258898033da8af968a881702b52e3-866x878.jpg?auto=format)

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

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

![Added modules](https://cdn.sanity.io/images/6ct6b26e/help-center-prod/2e965454ff2f108fa47e04a74fb632959ae11284-2090x508.jpg?auto=format)

**▸ 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](https://github.com/klaviyo/klaviyo-api-python) 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](https://pypi.org/project/klaviyo-api).

### 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*](https://www.npmjs.com/package/klaviyo-api)[ JavaScript module](https://www.npmjs.com/package/klaviyo-api).

```javascript
import { Metrics } from 'klaviyo';

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

```

View the [available Klaviyo objects and their methods](https://www.npmjs.com/package/klaviyo-api).

### 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](https://cdn.sanity.io/images/6ct6b26e/help-center-prod/1a778434d1cd20d294e2ce10d647e2f307fc114a-2042x736.jpg?auto=format)

2. Enter the variable’s **Key** and **Value**, then click **Save**.



![Key-value pairs set for environment variable ](https://cdn.sanity.io/images/6ct6b26e/help-center-prod/5d265b8414caeec9b2e3d46b6ed6410c49b38290-866x704.jpg?auto=format)

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

**📝 Note:** 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](https://cdn.sanity.io/images/6ct6b26e/help-center-prod/613afa1f42f5ed96bce017e03f12498f919fc9b0-2086x418.jpg?auto=format)

**📝 Note:** 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](https://cdn.sanity.io/images/6ct6b26e/help-center-prod/a3e53bb70723eebed667b59ce611a15aebbb2b2d-2008x730.jpg?auto=format)

2. 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](https://cdn.sanity.io/images/6ct6b26e/help-center-prod/9dce8d6f9c7d76a3426ab74edaab3e4adc21f207-580x902.jpg?auto=format)

3. Review the logs and any errors in the **Test output** panel.



![Test output](https://cdn.sanity.io/images/6ct6b26e/help-center-prod/70f7b8e2247cd59accd06cec1e215fdcc1316e73-1118x752.jpg?auto=format)

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](https://cdn.sanity.io/images/6ct6b26e/help-center-prod/952ba44cb037b530d329697d6b3c948de99ccf6a-1698x376.jpg?auto=format)

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.

**📝 Note:** 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](https://cdn.sanity.io/images/6ct6b26e/help-center-prod/6051d30bb00c55507c173288f1896f63ed8a4733-2958x1704.jpg?auto=format)

### 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](https://cdn.sanity.io/images/6ct6b26e/help-center-prod/bc7ca9f9adcbfe224f33a379306871de5b0e5515-1854x822.jpg?auto=format)

### 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](https://cdn.sanity.io/images/6ct6b26e/help-center-prod/52f79f020cb837f0a1831b95e191e839d66c3bf9-2512x888.jpg?auto=format)

### 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](https://cdn.sanity.io/images/6ct6b26e/help-center-prod/fe7d4e8e9caf39ba8ec7c5aba89f075da6f07ecd-2810x1042.jpg?auto=format)

4. 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.

5. Select the *Create function* button.

6. Once the function has been created, set the relevant environment variables so the function has the data it needs to run.

7. Test the function on the **Test** tab. After you confirm the expected result, select **Live** from the status dropdown.



**📝 Note:** 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](https://help.klaviyo.com/hc/en-us/articles/17655007276059.md)
  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](https://help.klaviyo.com/hc/en-us/articles/18622300908955.md)
  Learn about the differences between webhook solutions available in Klaviyo, and when you should use each one. 
