---
title: "Add a custom action to a flow"
description: "Execute pre-build or custom Python and Node.js action in flows with custom actions."
url: "https://developers.klaviyo.com/en/docs/add_a_custom_action_to_a_flow"
category: "Personalize messages"
lastUpdated: "2026-04-17"
related: ["https://developers.klaviyo.com/en/docs/llms.txt"]
---

# Add a custom action to a flow

> This is the Markdown version of https://developers.klaviyo.com/en/docs/add_a_custom_action_to_a_flow

Execute pre-build or custom Python and Node.js action in flows with custom actions.

> [!WARNING]
> Adding a custom action to a flow is a gated feature. To have access, you must have at least 400,000 active profiles in Klaviyo.

## You will learn

Learn how to add a custom action to a flow in Klaviyo that executes custom Python or Node.js code. Custom actions allow you to move data and build a personalized experience for your business.

## Before you begin

Custom actions require custom development and experience with either Python or Node.js. Klaviyo’s support team is unable to offer hands-on assistance. If you are not a developer, consider reaching out to a Klaviyo Partner for assistance.

## Custom action use cases

Example use cases for custom actions include:

- Normalizing _Placed Order_ values across storefronts that use different currencies.
- Mark coupons as used once they are redeemed in an order.
- Get weather information to use in personalizing content based on users location.
- Modifying an event payload and forwarding to an external webhook endpoint.
- Saving parts of an event payload as customer profile properties.
- Using GPT-3 to generate personalized text that thanks a customer for their order.
- Setting a customer's birthdate on their profile after they sign up.
- Sending a Slack or Microsoft Teams notification in response to a given event.

## Add a custom action to your flow

1. Navigate to a specific flow.
2. In the flow builder, drag and drop a **Custom Action** into the flow.

<img src = "https://files.readme.io/5725239397400ebc9153306b4f852ee89023115ae5c0faac2d3fb8ed97349550-custom_action_flow_builder.png" alt="Custom action in the flow builder" style="width:470px;height:454px;">

3. In the sidebar that appears, select either **Python** or **Node.js**.

<img src = "https://files.readme.io/e5673a0145705408d191da3f950b6fced20c534b9f81fc7e0b943ed4c79b5d80-blankpythonfunc.png" alt="Selecting Python or Node.js" style="width:392px;height:258px;">

4. Click on a prebuilt action or a blank Python or Node.js action. 

> [!NOTE]
> If you need help designing an action from scratch, view a prebuilt action as an example. Each example includes a _Readme_ section explaining the action.

<img src="https://files.readme.io/8911b87010f3cdb1aa898acc79c00f201b9a041050f378a7694aa8922a1a2c01-prebuiltfunc.jpeg" alt="Selecting the Birthdate Sync (Python) template" loading="lazy" />

5. In the modal showing the preview, click **Select**. After selecting an action, you will be brought to an interface with the following tabs:
   - Editor
   - Test output
   - Logs
   - Needs review  
     <br />

Read the sections below for information on each tab.

## Granting permissions to custom actions

The first time you create a new code function you will be asked to authenticate the Code OAuth application. This will allow the code functions you write to access data in your Klaviyo account on your behalf. Once you’ve granted Code access, you will be brought to the Code editor.

## Editor

The _Editor_ tab contains 3 sub-tabs:

- **Code**  
    The code tab has an editor where you can write Python or Javascript code.
- **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.
- **Output**
    Add up to 5 outputs that can be referenced by downstream actions in your flow.

## Code

In the _Code_ tab, you’ll see an editor you can use to write Python or Node.js functions that are executed in response to the selected topic.

<img src="https://files.readme.io/c240851588421b894cca0cce3355678849fbe72687d6ca1556a9ed9a6c56ceed-codeeditor.png" alt="Code editor page" loading="lazy" />

## Writing function code

In order for Klaviyo to execute the code you write, you need to wrap it in a function named `handler` that accepts 3 parameters:

- `event`  
  Consists of the event data associated with the triggering event in JSON:API format. If the trigger is non-event based (e.g., Added To List), then the value of this parameter will be `None` or `null` depending on the language.
- `profile`  
  The JSON:API profile object associated with the current evaluation. The schema of the profile object matches [the profile object returned by the Klaviyo API](https://developers.klaviyo.com/en/reference/get_profile.md).
- `context`  
  Contains additional metadata about the function execution

> [!WARNING]
> In Python, defining the `handler` is all that’s needed, but with Node.js, you must also `export` the function so that Klaviyo can access it. In Node.js, it’s good practice to declare your handler function as `async`, so that you can await Promises inside it.

### The `klaviyo` module

All functions come with a custom `klaviyo` package pre-installed into your code environment. The `klaviyo` 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 `klaviyo` module is the same as the `klaviyo` SDK object you would normally instantiate yourself using the `klaviyo-api` Python module. You can think of the `klaviyo` module as a pre-instantiated `klaviyo` SDK client.

For instance, 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, profile, 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, profile, context):
  print(klaviyo.Metrics.get_metrics())
```

Available API objects and their methods can be found at https://pypi.org/project/klaviyo-api.

#### Javascript `klaviyo` module

When using the built-in `klaviyo` module from your Javascript functions, just 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` JS module.

```javascript
import { Metrics } from 'klaviyo';
export default async (event, profile, context) => {
  console.log(await Metrics.getMetrics())
}
```
Available API objects and their methods can be found at https://www.npmjs.com/package/klaviyo-api.

## External modules

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

To add an external module to use in your code:

1. Click **Add module**.

<img src="https://files.readme.io/bc8b068b781aa56602e7489e0bd03fce1ec0a0edfce99a842292744a9232cbf8-addmodule.png" alt="Add a module page" loading="lazy" />

2. On the modal that appears, search and select the module you’d like to add:

<img src = "https://files.readme.io/d924253311908c291f8a7a610b385e33e29540d445764af679b591780fcac615-selectmodule.png" alt= "A=The action of adding a module" style="width:345px;height:349px;">

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

> [!NOTE]
> Refer to the external module’s native documentation for information regarding how to use it.

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

To add an environment variable:

1. Click **Add a variable**.

<img src="https://files.readme.io/11ab4e847d65afe16ca670b3474d000da7791d33744810757be7494d56a145b2-addenvvar.png" alt="Page for saving environment variables" loading="lazy" />

2. On the modal that appears, you can set a key-value pair for your environment variable.

<img src="https://files.readme.io/be577f949be9c3fe12cf30e84604e39a8b247eb16c48027d47bd82d7f2a98994-save_env_var_cust_action.png" alt="Save an environment variable page" loading="lazy" />

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

> [!NOTE]
> To access your environment variables in your code, use `os.getenv("Key")` for Python, or `process.env.Key`for Node.js.

<img src="https://files.readme.io/f8d738c9b17ee8254ec5994c69e5276a4fed21909e9aec1598d1917675e9a4b7-savedenvvar.png" alt="Environment Variables page" loading="lazy" />

## Test output

The _Test_ tab allows you to test your code with recent events to confirm that the output is behaving as expected.

To test your function:

1. Click **Run Test**.

<img src="https://files.readme.io/580e03b450806d390a026ea938fe44e9c9ce580b6bc9f4582148548a83c20810-runtest.png" alt="" loading="lazy" />

2. On the modal that appears, select a profile or event to test with. You can select profiles from the 10 most recent events captured in Klaviyo.

After selecting an event to test with, the test output will be shown.

<img src="https://files.readme.io/f3d545935b3787872697393f60cc91f3acab72dfc377665c961db5f9b187d6a9-testoutput.png" alt="Test output for a test event" loading="lazy" />

## Returning outputs from a custom action

Take your custom actions to the next level by returning data that can be referenced by downstream actions in your flow. You can create dynamic, personalized experiences by passing custom data from your code directly into your email templates.

> [!NOTE]
> Currently, outputs can be used in email actions, with support for profile property updates, SMS, and conditional split actions coming soon.

Here's how to set up and use outputs from your custom actions:

### 1. Configure your outputs

Navigate to the _Outputs_ tab to add up to 5 outputs that your function will return. Each output must have the following:
- **Name**: Any combination of characters a-zA-Z0-9_
- **Type**: One of "string", "number", or "boolean"  
- **Default value**: Used if your function fails to return an output as expected (e.g., if your function throws an error, times out, or returns an output of a different type)

<img src="https://files.readme.io/7dc81ab8b485505e6f159b92fb3a671f15fb8bb0c8cf1369db7efcd7bc1efdb8-outputs_page.png" alt="outputs page for custom actions" loading="lazy" />

### 2. Update your handler function

Update your custom action's `handler` function to return the configured outputs in a dictionary. The dictionary keys should be the names of the outputs you've configured and the values are the outputs themselves.

**Python example:**
```python
def handler(event, profile, context):
  # do some logic here
  return {
    "forecast_description": "Sunny",
    "forecast_temp": 25
  } 
```

**Node.js example:**
```javascript
export default async (event, profile, context) => {
  // do some logic here
  return {
    forecast_description: "Sunny",
    forecast_temp: 25
  }
}
```

### 3. Test your function outputs

To check if your function's outputs have been returned as expected, click the **Test** button in the upper right corner and choose a test event. Along with your function logs, you will be able to see your output data and validity based on your output configurations.

<img src="https://files.readme.io/1c56e48e148ae96d88658083aff21b3f207b7ed16ec782704bc4b5b28aff2e3b-test_event_page.png" alt="test event for checking output validity for custom action" loading="lazy" />

### 4. Use outputs in your email templates

When your flow evaluates, your function's outputs can be referenced by any downstream email templates in the flow. Outputs are exposed to your email templates as Django template variables using the syntax `{{outputs.<action_name>.<output_name>}}`. 

For example, if a custom action called "get_weather" returns an output called "forecast_temp", it can be used in a downstream email template via `{{outputs.get_weather.forecast_temp}}`.

<img src="https://files.readme.io/a52e2007de90fe8804a58fe66be9680409e6ce6821200ce0311e6f1da61e67e4-test_preview_output.png" alt="template with output for custom actions" loading="lazy" />

### Output validation and failure behavior

When a custom action with configured outputs is evaluated, the action will fail if the `handler` function fails to return all of the outputs as they were configured. The function will retry 3 times. If after 3 retries a valid set of outputs was still not returned, the configured "default_value" will be used for any outputs that were invalid.

## Logs

The _Logs_ tab shows the health of the currently viewed action. You’ll see:

- **Profile**  
  The email address of the profile associated with the given function execution. Click the email to navigate to the profile page.

- **Status**  
  The progress of a function’s execution.

- **Run ID**  
  The unique ID of this function execution. Click the ID to open a side drawer with  
  additional execution information, such as the function logs.

- **Response time**  
  The amount of time it takes for your code to execute in response to an event.

- **Date**  
  A timestamp of when the function was executed.

## Needs review

If the custom action is set to manual status, profiles will be queued in the _Needs Review_ tab to be manually approved for the code to execute.

## Deploy the action and set it live

1. In the code editor, click **Deploy** in the upper right to deploy your local code changes. Any changes will be preserved even if you leave the page, but only deployed changes will be reflected in subsequent flow evaluations. If you chose a prebuilt function and didn’t make any changes, it will automatically be deployed.

<img src="https://files.readme.io/7e64f59d1445017c2a561c5c588106e8035a1262e7d6ccc1af8656197ad7aaa2-deploycode.jpeg" alt="Deploying a custom action" loading="lazy" />

2. Click **Done** in the upper right.
3. Click on the custom action again in the flow builder.
4. In the sidebar, rename the action if desired.
5. Click the _Status_ dropdown to change the status from **Draft** to **Manual** or **Live**.

<img src = "https://files.readme.io/a0238f6700804e97708225c6a99856bd7e63492807f9b4ac53f362c95c969e47-cust_action_status.png" alt="Updating the action status to manual or live" style="width:381px;height:200px;">

6. Click **Save**.

## Limits

- Function timeout: `12` seconds
- Action rate limit: `10` evaluations per second
- Custom actions that fail due to a code error or timeout will retry up to 3 times with exponential backoff. The profile will not proceed through the flow until the custom action succeeds or the retry limit is hit.

## Additional resources

- [How to add a webhook action to a flow](https://developers.klaviyo.com/en/docs/how_to_add_a_webhook_action_to_a_flow.md).
- [How to add an update profile property action to a flow](https://help.klaviyo.com/hc/en-us/articles/360001768432)
- [How to add a internal alert action to a flow](https://help.klaviyo.com/hc/en-us/articles/360050242251)
