# Klaviyo Developers: the essentials in full > The guides an agent needs before calling the Klaviyo REST API, revision 2026-10-15 (getting started, authentication, versioning, rate limits and errors, the JSON:API features and the SDKs), then every agent skill's SKILL.md, in one Markdown file. The whole site is too large for one file, so the last section links the files that hold the rest in full, with their sizes. https://developers.klaviyo.com/llms.txt links the Markdown version of every page. --- # Get started with Klaviyo > This is the Markdown version of https://developers.klaviyo.com/en/docs/get_started Create a private API key and make your first call to the Klaviyo API in a few minutes. ## You will learn Klaviyo is a customer platform for email, SMS and push marketing, built on the data your customers create. The Klaviyo API lets your code read and change that data: profiles, events, lists, catalogs, campaigns and more. In this quickstart, you'll create a private API key, use it to create a list, and check that the list appears in Klaviyo. It takes about five minutes. > [!NOTE] > Building with an AI agent? See [Set up your AI agent](https://developers.klaviyo.com/en/docs/agent_setup.md) to give it these docs as Markdown, the OpenAPI spec and Klaviyo's MCP server. ## Before you begin You need a Klaviyo account. To keep test data out of your production account, [create a test account](https://developers.klaviyo.com/en/docs/create_a_test_account.md) first, and use it for every step below. Creating an API key takes an Owner, Admin or Manager role on the account. Without one, ask someone who has one to create the key in Step 1 for you. ## Step 1: Create a private API key Server-side code authenticates with a private API key. 1. In Klaviyo, go to **Settings** and select **[API keys](https://www.klaviyo.com/settings/account/api-keys)**. 2. Under *Private API Keys*, select **Create Private API Key**. 3. Name the key, then choose **Custom Key** and give **Lists** full access. This quickstart only needs the `lists:read` and `lists:write` scopes. 4. Select **Create**, and copy the key to a secure location. Klaviyo doesn't show it again. A private key starts with `pk_`. Never put it in code that runs in a browser or a mobile app; those use the account's public key with the client endpoints instead. See [Authenticate API requests](https://developers.klaviyo.com/en/docs/authenticate_.md) for both. ## Step 2: Create a list Send a [Create List](https://developers.klaviyo.com/en/reference/create_list.md) request, replacing `your-private-api-key` with your key: ```bash curl --request POST \ --url https://a.klaviyo.com/api/lists \ --header 'Authorization: Klaviyo-API-Key your-private-api-key' \ --header 'accept: application/vnd.api+json' \ --header 'content-type: application/vnd.api+json' \ --header 'revision: 2026-10-15' \ --data '{"data": {"type": "list", "attributes": {"name": "My first API list"}}}' ``` Every request sends: - `Authorization`: your private key, after `Klaviyo-API-Key`. - `revision`: the API revision your code is written against. Klaviyo releases a new revision each quarter; see the [changelog](https://developers.klaviyo.com/en/docs/changelog_.md) for what each one changed. - `accept` and `content-type`: the API uses [JSON:API](https://jsonapi.org), so request and response bodies are `application/vnd.api+json`. A successful request returns `201 Created` and the new list, including its ID. Trimmed to those fields, the body looks like this: ```json { "data": { "type": "list", "id": "Y6nRLr", "attributes": { "name": "My first API list" } } } ``` A `401` response means the key is missing or wrong, and a `403` that it doesn't have the `lists:write` scope. See [Rate limits and error handling](https://developers.klaviyo.com/en/docs/rate_limits_and_error_handling.md) for every status code the API returns. ## Step 3: Check the result Get the new list with [Get List](https://developers.klaviyo.com/en/reference/get_list.md), replacing `your-list-id` with the ID from Step 2: ```bash curl --request GET \ --url https://a.klaviyo.com/api/lists/your-list-id \ --header 'Authorization: Klaviyo-API-Key your-private-api-key' \ --header 'accept: application/vnd.api+json' \ --header 'revision: 2026-10-15' ``` The response has the list you created, named "My first API list". You can also find it in Klaviyo under **Audience** > **Lists & segments**. ## Next steps - **Use an SDK.** Klaviyo's SDKs for Python, Node.js, Ruby and PHP set the headers for you: [Install a library](https://developers.klaviyo.com/en/docs/install_a_library.md). - **Add test data.** [Generate sample data](https://developers.klaviyo.com/en/docs/generate_sample_data.md) fills a test account with sample Klaviyo, ecommerce and catalog data to build against. - **Learn the data model.** [Klaviyo's data model](https://developers.klaviyo.com/en/docs/introduction_to_klaviyos_data_model.md) explains how profiles, events, metrics and lists relate, and [Klaviyo's architecture](https://developers.klaviyo.com/en/docs/klaviyos_architecture.md) how data flows through Klaviyo. - **Explore the API.** The [API reference](https://developers.klaviyo.com/en/reference.md) covers every endpoint, and [Klaviyo's Postman collections](https://developers.klaviyo.com/en/docs/use_klaviyos_postman_collections.md) let you try them without code. - **Build an integration.** If you're building an app for other Klaviyo accounts, see the [partner resources](https://developers.klaviyo.com/en/docs/build_your_integration.md). - **Take the developer certificate.** The [Klaviyo developer certificate](https://academy.klaviyo.com/klaviyo-developer-certificate?utm_source=dev_portal&utm_medium=referral&utm_campaign=developer_cert) covers Klaviyo's data model, its server-side and client-side APIs, and troubleshooting. ## Not a developer? The [Help Center](https://help.klaviyo.com/hc/en-us) has how-to guides for using Klaviyo and connecting its built-in integrations. The [API fundamentals for marketers](https://academy.klaviyo.com/en-us/collections/api-fundamentals-for-marketers) learning path covers how to use and troubleshoot Klaviyo's API endpoints. --- # Authenticate API requests > This is the Markdown version of https://developers.klaviyo.com/en/docs/authenticate_ Learn how to authenticate requests to Klaviyo's server- and client-side endpoints. ## You will learn After reading this article, you will be able to distinguish which methods of authentication you should use for making calls with Klaviyo's server- and client-side APIs. You will also learn how to set custom scopes to protect you and your customers’ data. ## Server-side vs client-side APIs > [!NOTE] > Check out our video on client- and server-side tracking with Klaviyo's APIs. A majority of Klaviyo’s APIs are server-side endpoints, which should be securely handled on your server rather than exposed in the browser. Handle sensitive information via server-side APIs, like bulk-creating events for one or more profiles. Client-side APIs are used to track and send user behavior data from the client to Klaviyo. They are designed to be called from publicly-searchable, client-side environments only (see [Client API reference](https://developers.klaviyo.com/en/reference/create_client_subscription.md)). Klaviyo provides 3 methods of authentication including private key authentication and OAuth (used to call server-side APIs) and public key authentication (used to call client-side APIs). Read the table below to learn more about how each method can be used for authenticating API calls:
Server-side APIs Client-side APIs
Private key authentication
All /api endpoints use API private keys to authenticate requests. If you do not use an API key for your requests, or if you use a key from the wrong account, your call will return an error. A 401 error indicates an invalid or missing API key.
OAuth
If you are a tech partner integrating with Klaviyo, we recommend using OAuth to make authorized API calls. OAuth offers multiple benefits over a private key integration, including security, usability, improved rate limits, and the ability to be listed in Klaviyo's App Marketplace.
Public key authentication
All /client endpoints use a public API key: your 6-character company ID, also known as a site ID. We recommend using the Klaviyo object or our Mobile SDKs for interacting with our client-side APIs.
> [!NOTE] > To manage API keys, you must have an Owner, Admin, or Manager role on your Klaviyo account. ## Private key authentication Private API keys can be used to read and write data to your Klaviyo account. Klaviyo allows you to generate multiple private keys for your applications. > [!WARNING] > For your account's security, your private API keys should never be used with Client endpoints, exposed in client-side code, or made accessible from public repositories. ### Create a private key To create a private key: 1. Navigate to your account’s *Settings* page and select **[API keys](https://www.klaviyo.com/settings/account/api-keys)**. 2. Under the *Private API Keys* section, select **Create Private API Key**. Settings page with button to create a private API key. 3. Provide a name for your private key and add any of the following scopes: * Custom Key \ Allows you to decide how much access to give the third party. * Read-Only Key \ Only allows third parties to view all data associated with the endpoint. * Full Access Key \ Allows third parties to create, delete, or make changes to anything associated with that endpoint. > [!WARNING] > Note that you cannot add a scope to an existing private key. You also cannot edit a private API key after it’s been created. If you need to remove access to a key based on its current scope, delete it and then create a new key with the correct scope. 4. When you have finished setting your key’s scopes, select **Create**. To protect your account from unauthorized access, you cannot view your private API keys in Klaviyo. After you have created your private API key, copy it to a secure location. Created private key with its Read/Write access endpoints. Private keys will have the prefix pk_ followed by a longer alphanumeric string. ### Use a private key Private key authentication for `/api` endpoints is performed by setting the following request header: ``` Authorization: Klaviyo-API-Key your-private-api-key ``` ```curl curl --request GET \ --url https://a.klaviyo.com/api/{endpoint}/ \ --header 'Authorization: Klaviyo-API-Key your-private-api-key' \ --header 'accept: application/json' \ --header 'revision: 2026-10-15' ``` ## Public key authentication Your 6-character public key, sometimes referred to as a site ID, is a short alphanumeric string that serves as the unique identifier for your Klaviyo account. Public keys cannot be used to access secure data in your account and are safe to share. Use your public key when you need to track people and events in client-side JavaScript code. Client-side API calls only require a public API key, also known as a `company_id`, for authentication: ```curl curl --request POST \ --url 'https://a.klaviyo.com/client/subscriptions/?company_id=PUBLIC_API_KEY' \ --header 'content-type: application/json' \ --header 'revision: 2026-10-15' \ --data ' ... ``` ## OAuth If you're building an app with Klaviyo, use [OAuth](https://developers.klaviyo.com/en/docs/set_up_oauth.md) to provide secure delegated access to users via access tokens (required to enter Klaviyo’s App Marketplace). When setting up OAuth, you must provide designated scopes for each API authorization request you'll want to make. ## Set custom scopes Setting custom scopes helps you protect your and your customers’ data by limiting what third parties can access. When requesting authorization to make API calls (OAuth), you should only request the scopes required to use your app. View the API reference documentation to understand which scopes you’ll need to define. For example, if your private key or Klaviyo app needs to create lists, your app needs the `lists:write` scope as shown in the following API reference documentation for the Create List endpoint: Create List API reference docs with lists:write scope highlighted See the full list of scopes needed for each of our APIs below:
Available scopes for each API 

API endpoint Associated scopes
Accounts accounts:read
Campaigns campaigns:read

campaigns:write

Conversations conversations:read

conversations:write

Catalogs catalogs:read

catalogs:write

Coupons coupons:read

coupons:write

Coupon codes coupon-codes:read

coupon-codes:write

Data privacy data-privacy:read

data-privacy:write

Events events:read

events:write (allows for creating/updating profiles)

Flows flows:read

flows:write

Forms forms:read
Images images:read

images:write

Lists lists:read

lists:write

Metrics metrics:read

metrics:write

Profiles profiles:read

profiles:write

Push tokens push-tokens:read

push-tokens:write

Reporting campaigns:read
flows:read

forms:read
segments:read

Reviews reviews:read

Segments segments:read

segments:write

Subscriptions subscriptions:read

subscriptions:write

Tags tags:read

tags:write

Templates templates:read

templates:write

Tracking Settings tracking-settings:read

tracking-settings:write

Web Feeds web-feeds:read

web-feeds:write

## Additional resources * [Make API calls with OAuth](https://developers.klaviyo.com/en/docs/set_up_oauth.md) * [Use Klaviyo's Postman collections](https://developers.klaviyo.com/en/docs/use_klaviyos_postman_collections.md) * [Introduction to the Klaviyo object](https://developers.klaviyo.com/en/docs/introduction_to_the_klaviyo_object.md) --- # Make a test API request > This is the Markdown version of https://developers.klaviyo.com/en/docs/make_your_first_api_call Test your connection via API request, confirm your authentication is working, and that your application can connect with Klaviyo's servers. ## Test POST request ```prompt Make a test request to the Klaviyo API Make a test request to the Klaviyo API that creates a list, to check that my private API key works. First read https://developers.klaviyo.com/en/docs/make_your_first_api_call.md. Ask me for these before you change anything, unless I've already given them: - The name of the environment variable that holds my private API key. If I'm using a test account, the key must belong to that account. - A name for the test list. Then: 1. Send `POST https://a.klaviyo.com/api/lists/` with these headers: `Authorization: Klaviyo-API-Key `, `accept: application/json`, `content-type: application/json`, and `revision` set to the latest API revision, a date such as `2026-10-15`, which https://developers.klaviyo.com/en/reference/api_overview.md gives. 2. Send this body: `{"data": {"type": "list", "attributes": {"name": ""}}}`. The name is required. 3. Use curl unless I ask for a script. If I do, write it in this codebase's language, following its conventions. 4. Read the key from the environment variable in the command itself. Don't paste it into the command, print it, or write it to a file, and don't commit it. 5. Send the request once. It creates a real list in the account, so don't repeat it or send any other requests. A successful response returns the new list's `id` and its `name`, `created` and `updated` attributes. If you get an error, show me the error body and what you think caused it. When you're done, tell me the list ID and what you ran. Remind me to check the list exists by searching for its name in Lists & Segments (https://www.klaviyo.com/lists) in the account. ``` To check that your integration is working correctly, make a test request to the List API using the code below to create a new list. Replace `your-private-api-key` with your own private API key. If you are using a test account, first check the key is associated with your test account. A successful request returns the list ID of the newly created list, as well as its associated attributes. ```curl curl --request POST \ --url https://a.klaviyo.com/api/lists/ \ --header 'Authorization: Klaviyo-API-Key your-private-api-key' \ --header 'accept: application/json' \ --header 'content-type: application/json' \ --header 'revision: 2026-10-15' \ --data ' { "data": { "type": "list", "attributes": { "name": "THIS IS REQUIRED" } } } ``` ```python import requests url = "https://a.klaviyo.com/api/lists/" payload = {"data": {"type": "list"}} headers = { "accept": "application/json", "revision": "2026-10-15", "content-type": "application/json", "Authorization": "Klaviyo-API-Key your-private-api-key" } response = requests.post(url, json=payload, headers=headers) print(response.text) ``` ```php request('POST', 'https://a.klaviyo.com/api/lists/', [ 'body' => '{"data":{"type":"list"}}', 'headers' => [ 'Authorization' => 'Klaviyo-API-Key your-private-api-key', 'accept' => 'application/json', 'content-type' => 'application/json', 'revision' => '2026-10-15', ], ]); echo $response->getBody(); ``` ```ruby require 'uri' require 'net/http' require 'openssl' url = URI("https://a.klaviyo.com/api/lists/") http = Net::HTTP.new(url.host, url.port) http.use_ssl = true request = Net::HTTP::Post.new(url) request["accept"] = 'application/json' request["revision"] = '2026-10-15' request["content-type"] = 'application/json' request["Authorization"] = 'Klaviyo-API-Key your-private-api-key' request.body = "{\"data\":{\"type\":\"list\"}}" response = http.request(request) puts response.read_body ``` ```json Success { "data": { "type": "list", "id": "string", "attributes": { "name": "string", "created": "2022-10-19T16:10:03.923Z", "updated": "2022-10-19T16:10:03.923Z" }, "links": { "self": "string" } } } ``` ## Test with Postman Before you begin testing with Postman, check out our [guide on how to use our Postman collections](https://developers.klaviyo.com/en/docs/use_klaviyos_postman_collections.md). Fork our latest collection of prebuilt API requests into your personal workspace to get started. To confirm that your application can send data to Klaviyo, open the **Lists & Segments** folder and select the **Create List** POST request. Replace `your-private-api-key` with a private API key from your account. If you are using a test account, first check the key is associated with your test account. When you are ready, click **Send**. A successful request returns the list ID of the newly created list. ```json Success { "data": { "type": "list", "id": "string", "attributes": { "name": "string", "created": "2022-10-19T16:10:03.923Z", "updated": "2022-10-19T16:10:03.923Z" }, "links": { "self": "string" } } } ``` ## Confirm success in account Double-check that your test request successfully created a list in your preferred account. While logged in to your account, navigate to **Lists & Segments** a search for the name of your newly-created list to verify. Lists and Segments tab in Klaviyo with Test List visible --- # API overview > This is the Markdown version of https://developers.klaviyo.com/en/docs/api_overview > [!NOTE] > **Jumpstart your Klaviyo API journey with our YouTube tutorials.** > Dive into Klaviyo's API tutorial playlist on YouTube, where we provide walkthroughs of some of our most popular Klaviyo API endpoints. ## Quickstart 1. **New Klaviyo developers:** Check out our [Get started with Klaviyo](https://developers.klaviyo.com/en/docs/get_started.md) series to set up an account, obtain API credentials, and authenticate. 2. **Current Klaviyo developers:** - Install one of our [new SDKs](https://developers.klaviyo.com/en/docs/sdk_overview.md). - Make test calls with the [new API collection in our Postman workspace](https://www.postman.com/klaviyo/workspace/klaviyo-developers/overview). 3. **To learn more, see below for an overview of the newly launched API features:** - Go into detail on the [JSON API features](https://developers.klaviyo.com/en/docs/json_api_feature_guides.md) supported by our new API surface. ## OpenAPI and Postman [View the latest OpenAPI spec here.](https://github.com/klaviyo/openapi) Import the spec into your favorite API tool, such as Postman, to start interacting with our new APIs right away. You can also navigate to our [Postman Workspace](https://www.postman.com/klaviyo/workspace/klaviyo-developers/overview), where you will find our latest collection of requests, along with the API definitions. You can get started by checking out our [Postman collection guide](https://developers.klaviyo.com/en/docs/use_klaviyos_postman_collections.md). ## Authentication Klaviyo provides 3 methods of authentication including private key authentication and OAuth (used to call server-side APIs) and public key authentication (used to call client-side APIs). Read below for a quick overview of each method. ### Private key authentication All `/api` endpoints use [private API keys](https://developers.klaviyo.com/en/docs/authenticate_.md) with API key scopes to authenticate requests. If you do not use an API key for your requests, or if you use a key from the wrong account, your call will return an error. A `401` error indicates an invalid or missing API key. Private key authentication for `/api` endpoints is performed by setting the following request header: ``` Authorization: Klaviyo-API-Key your-private-api-key ``` ### OAuth If you are a tech partner integrating with Klaviyo, we recommend using OAuth to authenticate your app. OAuth offers multiple benefits over a private key integration, including security, usability, and improved rate limits. Check out our [guide on setting up OAuth](https://developers.klaviyo.com/en/docs/set_up_oauth.md). ### Public key authentication All `/client` endpoints are designed to only be called from publicly-browseable client-side environments and use public API keys to authorize and route requests. Your public API key is your 6-character company ID, also known as a site ID. We recommend using the [Klaviyo object](https://developers.klaviyo.com/en/docs/introduction_to_the_klaviyo_object.md) or our [mobile SDKs](https://developers.klaviyo.com/en/docs/sdk_overview.md) for interacting with our client-side APIs. Public API keys are passed to `/client` endpoints using a query parameter: ``` curl --request POST \ --url 'https://a.klaviyo.com/client/events/?company_id=COMPANY_ID' --header 'Content-Type: application/json' --data '{DATA}' ``` > [!NOTE] > Client endpoints are specifically designed to limit functionality to object creation of specific types of objects and do not respond with any potentially sensitive response data. For security reasons, this data must be accessed using private key endpoints only (i.e., `/api`). ## API key scopes Klaviyo's APIs support the use of API scopes, which allow you to restrict access for third parties using a private API key. Adding a scope helps you protect your and your customers’ data by limiting what third parties can access. You can add any of the following scopes to any new private API key in Klaviyo: - **Read-only** Only allows third parties to view all data associated with the endpoint - **Full** Allows third parties to create, delete, or make changes to anything associated with that endpoint (set by default) - **Custom** Allows you to decide how much access to give the third party Note that you cannot add a scope to an existing private key. You also cannot edit a private API key after it’s been created. If you need to remove access to a key based on its current scope, delete it and then create a new key with the correct scope. For more information about the supported scopes for each endpoint and how to add a scope to an API key, please refer to the Authenticate API requests guide. ## Versioning and deprecation Check out our [API versioning and deprecation policy](https://developers.klaviyo.com/en/docs/api_versioning_and_deprecation_policy.md) to learn about how Klaviyo handles API versioning and support. ## Status codes and errors Every response will include an HTTP status code with more details on whether the request succeeded. Check out [our guide on status codes and errors](https://developers.klaviyo.com/en/docs/rate_limits_and_error_handling.md) to learn more about status codes used by Klaviyo’s APIs and how to troubleshoot error responses. ## Rate limiting All new API endpoints are [rate limited](https://developers.klaviyo.com/en/docs/rate_limits_and_error_handling.md) on a per-account basis, and use a fixed-window rate limiting algorithm with two distinct windows: burst (short) and steady (long). All API traffic will be subject to rate limits, and will receive `HTTP 429` errors in the event either a burst or steady rate limit is reached. Each endpoint lists its burst and steady rate limits in our API reference documentation. ## JSON:API feature guides ### Relationships Klaviyo’s modern APIs offer powerful functionality via the `relationships` object, a thorough set of syntax offered by JSON:API for modeling relationships between resources. This syntax allows developers to efficiently query specific groups of related resources, eliminating the need to perform redundant queries. Check out our [guide on JSON:API relationships](https://developers.klaviyo.com/en/docs/relationships_.md) for more information on how use, create, modify, and delete resource relationships. ### Filtering JSON:API’s general filtering syntax and its supported operations can be used across all new APIs. Please note that support for specific operators and fields is highly specific to each endpoint. You can refer to the `filter` query parameter in the API reference documentation for specific operator and field support. [View our JSON:API filtering guide](https://developers.klaviyo.com/en/docs/filtering_.md) for a list of the filter operations and comparison literals. The filtering syntax for Klaviyo’s new APIs uses the `?filter` query parameter for all endpoints that support filter operations. ![](https://files.readme.io/064bb96-image.png) ### Sorting Where supported, sorting is handled using the `?sort` query parameter followed by a field name. Reverse sorting is specified using a `-` prefix. **Example** `GET /api/events/?sort=datetime` sorts `events` by `datetime` ascending; `GET /api/events/?sort=-datetime` sorts by `datetime` descending. For more examples, view our JSON:API sorting guide. ### Sparse fieldsets Several endpoints support [sparse fieldsets](https://jsonapi.org/format/#fetching-sparse-fieldsets) to allow developers to select only requested fields of resources, rather than having to retrieve entire resources (which may be very large). Sparse fieldsets are specified using the `?fields[TYPE]=field1,field2` query parameter, where `TYPE` is the resource type from which to select only `field1` and `field2`. This also works for included resource types, e.g. `?fields[INCLUDED-TYPE]=field1,field2`; however you also need to include that resource in your request, using the `include` query parameter for this to work. **Examples**: 1. `GET /api/events?fields[event]=metric_id,profile_id` will retrieve only the `metric_id` and `profile_id` attributes for all events returned in the response. 2. `GET /api/events?fields[profile]=first_name,email&include=profile` will retrieve all `event` fields and only the `first_name` and `email` attributes for included `profile` resource data. To learn more about sparse fieldsets, see our JSON:API sparse fieldsets guide. ## Pagination Our APIs support _cursor-based pagination_ with the query parameter `?page[cursor]`. Paginated resource responses will contain a specific set of pagination cursor helper links in their top-level `links` object, like the following: ```json { "data": [ ... ], "links" : { "next" : "https://a.klaviyo.com/api/profiles/?page%5Bcursor%5D=bmV4dDo6aWQ6Ok43dW1iVw", "prev" : null, "self" : "https://a.klaviyo.com/api/profiles" } } ``` Use these links to navigate to next and previous pages. ## Datetimes ### Datetime formatting All [datetimes](https://developers.klaviyo.com/en/docs/datetimes_.md) across all new APIs in URLs, request, and response bodies must be formatted as [ISO 8601 RFC 3339](https://datatracker.ietf.org/doc/html/rfc3339) datetime strings. **Example:** `2023-01-16T23:20:50.52Z` --- # API versioning and deprecation policy > This is the Markdown version of https://developers.klaviyo.com/en/docs/api_versioning_and_deprecation_policy Learn about how we version and support our APIs. Klaviyo’s APIs evolve and change over time. Our versioning and deprecation policy details how we choose to version our APIs and offer developer support as we continually improve and expand our functionality. You’ll learn about how we safely introduce changes to our APIs and discover our API lifecycle so that you can most effectively manage your Klaviyo API usage. For more information, refer to our [API Terms of Use](https://www.klaviyo.com/legal/api-terms). To stay up-to-date on API changes, be sure to: - Subscribe to our [developer newsletter](https://manage.kmail-lists.com/subscriptions/subscribe?a=9BX3wh&g=SaqhYy). - Join our [Klaviyo Community developer group](https://community.klaviyo.com/groups/developer-group-64). - Regularly check our [changelog](https://developers.klaviyo.com/en/docs/changelog_.md). ## API versioning We version our APIs with _revisions_, or snapshots of our API at a point in time. Revisions are formatted as ISO 8601 dates (representing release dates) and passed using the HTTP request header, `revision` (for example, `2023-12-15)`. This versioning scheme allows us to regularly release new functionality without negatively impacting developers using older revisions. The following request includes a revision header that serves our `2023-12-15` revision: ```json Request curl --request GET \ --url https://a.klaviyo.com/api/events/ \ --header 'Authorization: Klaviyo-API-Key your-private-api-key' \ --header 'accept: application/json' \ --header 'revision: 2023-12-15' ``` > [!NOTE] > Note that the revision passed in must be a valid revision. You can quickly check for valid revisions and view their supporting documentation in the revision drop down in the top left. > > > [!NOTE] > If you are using a revision that was released before the 2023-07-15 revision, we recommend [learning about the breaking changes released](https://developers.klaviyo.com/en/docs/migrate_to_2023_07_15_relationships.md) and upgrading to our latest revision. ### Beta revisions For testing and feedback purposes, we share our new APIs with developers in an early access state. After this phase, we may share the new APIs in a public beta. Klaviyo APIs in beta are accessible via beta revision headers with the suffix `.pre`, for example, `2024-02-15.pre`. We release supporting reference documentation alongside our beta APIs and [encourage developer feedback](https://community.klaviyo.com/groups/developer-group-64). > [!WARNING] > Note that beta revisions are not considered stable and should not be used in production. ## Breaking changes Klaviyo defines a breaking change as any modification to or deletion of functionality within an API that may cause integrations or applications to function abnormally or break. Examples of breaking changes include, but are not limited to: - Renaming of a URL, request or response field, HTTP header, or query parameter. - Removal of a request or response field, HTTP header, or query parameter. - Addition of a required request field, HTTP header, or query parameter. - Removal of an endpoint. Breaking changes are generally gated behind a new revision and clearly documented in our [changelog](https://developers.klaviyo.com/en/docs/changelog_.md). If we plan on introducing a breaking change to an existing revision, we will provide **30 days notice** to our developers. Be sure to join our [developer newsletter](https://manage.kmail-lists.com/subscriptions/subscribe?a=9BX3wh&g=SaqhYy) to receive important updates. > [!NOTE] > If you detect an undocumented change causing breakages in your app, please share it with us on our [Klaviyo Community developer group](https://community.klaviyo.com/groups/developer-group-64). Any undocumented functionality is not supported and should not be relied upon. ## Non-breaking changes Klaviyo considers the following classes of changes to be non-breaking changes: - New optional fields in endpoint request payloads - New fields added to endpoint response payloads - Updating the `detail` string for an error - New values for an existing enum field for endpoint request or response payloads - New members for an existing complex union type field for endpoint request or response payloads, e.g. a new segment condition - New optional query parameters - New optional request headers - Additional response headers - New endpoints Generally, new endpoints are only released in new revisions. Note that non-breaking changes to existing endpoints may be released within an existing revision. > [!NOTE] > While non-breaking changes are not expected to be disruptive to existing functionality, it is still possible that they can cause breakages in your application. Be sure to build your application to adapt to non-breaking changes at your own discretion. ## SDK versioning When a new API revision is released, we release new versions of our [SDKs](https://developers.klaviyo.com/en/docs/install_a_library.md). Our SDKs follow [semantic versioning](https://semver.org/), or the major.minor.patch format, where each numeric value is incremented to reflect the following changes: - **major** The API revision contains at least one breaking change. - **minor** The API revision contains non-breaking changes, such as notable new functionality. - **patch** The SDK has been updated with bug fixes. Note that SDK support relies on our API versioning and deprecation policy, as each SDK version is pinned to a specific API revision. Keep in mind that each SDK has a separate changelog for documenting changes between versions. ## API lifecycle > [!NOTE] > Klaviyo provides developers **2 years** to update their apps and integrations before a revision is retired and access is removed. View our revision lifecycle example below to learn about how each of our revisions is supported from initial release to retirement. As shown in the example above, a revision goes through the following phases: - **Stable** - The revision is subject to non-breaking changes, but remains largely unchanged. - Lasts for 1 year after release. - **Deprecated** - Use of the revision is discouraged over stable revisions - At this point, you should plan to migrate your apps to our latest stable revision before the revision is retired to avoid breakages. - Starts 1 year after release. Lasts for 1 year. - **Retired** - 2 years after release, the revision is no longer supported, and breakages are likely to occur in any apps/integrations that rely on it. - Calls to endpoints that have been removed since this revision will receive a 410 error. > [!NOTE] > For any net-new integrations, we recommend starting with our latest stable revision. ### Initial release When new endpoints and/or breaking changes are added to our APIs, they are released in a new revision. When a new revision is released: - It is the latest stable revision until a newer revision is released. - There should not be any breaking changes made to the revision, but there may be some non-breaking changes over time. - The revision remains stable for **1 year**. ### Deprecation After a revision’s stable period (1 year after its initial release), the revision is deprecated (set to retire). At this point, you should plan to upgrade your apps to our latest stable revision, which will include new and improved functionality over any deprecated revisions. When a revision becomes deprecated: - You’ll have **1 year** to upgrade your apps before the revision is retired. - The revision will not receive any further updates or bug fixes. - The documentation is updated with the new revision or notifies users that the documented method is deprecated. > [!NOTE] > Any new integrations and API usages should be built with our latest revision. You can view recent API requests by revision header, among other API activity data, with our [API usage tools](https://developers.klaviyo.com/en/docs/monitor_api_usage.md). ### Retirement After a revision’s year-long deprecation phase, it is retired, meaning it is unsupported and no longer available for use. We do our best to fall-forward to the oldest non-retired revision (see below); however, calls to retired endpoints that have been removed since that revision will receive a 410 error, and other breakages are likely to occur. ### Fall-forward behavior If a retired revision date is passed to the request header, Klaviyo falls forward and responds to your request with the same behavior as the next oldest revision. For example, when revision`2023-06-15` retires, the next oldest revision is `2023-07-15`, and any API requests to `2023-06-15` will be served `2023-07-15`. > [!WARNING] > Relying on fall-forward behavior is likely to introduce unwanted, breaking changes in your app. It’s much safer to pin a static revision and connect your apps to our latest revision every 12-18 months. This will give you enough time to revisit your implementation to take advantage of improved functionality and address any potential breaking changes. If you would like to opt out of this behavior, you can use the following request header: `X-Klaviyo-Revision-Fall-Forward-Opt-Out:1` > [!WARNING] > Note that if you choose to opt out of fall-forward behavior, when a revision is retired, all requests to it will result in a 410 error and cause breakages in your app. Our fall-forward behavior is a best-effort attempt to honor your request and not fully break your integration; however, we strongly recommend that you audit and update your API usage prior to a revision’s retirement, as it is likely that functionality will break or work differently in newer revisions. ## Additional resources - [API overview](https://developers.klaviyo.com/en/reference.md) - [Monitor API usage](https://developers.klaviyo.com/en/docs/monitor_api_usage.md) - [Migrate from v1/v2 to new Klaviyo APIs](https://developers.klaviyo.com/en/docs/migrating_from_v1v2_to_the_new_klaviyo_apis.md) --- # Rate limits, status codes, and errors > This is the Markdown version of https://developers.klaviyo.com/en/docs/rate_limits_and_error_handling Refer to our list of status codes, error responses, rate limits, and ingestion limits for troubleshooting help. ## Rate limits Klaviyo's APIs employ rate limits against bursts of incoming traffic to help maximize its stability. Rate limits for specific endpoints can be found in the API reference for each endpoint. All new API endpoints are rate limited on a _per-account_ basis, and use a fixed-window rate limiting algorithm with two distinct windows: burst (1-second window) and steady (1-minute window). All API traffic will be subject to these rate limits, and will receive `HTTP 429` errors in the event either a burst or steady rate limit is reached. Unless otherwise documented, all API endpoints use one of the following rate limits: - **XS**: 1/s burst; 15/m steady - **S**: 3/s burst; 60/m steady - **M**: 10/s burst; 150/m steady - **L**: 75/s burst; 700/m steady - **XL**: 350/s burst; 3500/m steady > [!NOTE] > [Rate limiting for OAuth apps](https://developers.klaviyo.com/en/docs/handle_your_apps_oauth_flow.md) differs from our standard API rate limiting for detailed above. OAuth apps receive their own rate limit quota per installed app instance (i.e., per account per app), while private key integrations share the same rate limit quota per account. All non-rate-limited (i.e., non 429) responses will contain the following HTTP response headers that indicate the state of the _steady rate limit window_ to the client. We recommend using these headers to manage your request rate, especially if you maintain a third-party application that makes requests on behalf of Klaviyo customers: - `RateLimit–Limit`: The number of requests allowed per time period - `RateLimit-Remaining`: The approximate number of requests remaining within a window - `RateLimit-Reset`: Number of seconds remaining before current window resets Treat these limits as maximums and don’t generate unnecessary load. > [!NOTE] > Note that the `RateLimit-Limit`, `RateLimit-Remaining`, and `RateLimit-Reset` headers are not returned when you actually hit a `HTTP 429` error. When you hit the error, those headers are replaced with a `Retry-After` header that returns an `int` indicating the number of seconds before you can start making requests. ## Query Param Rate Limits As part of our recent release raising the rate limits for several endpoints, we have also introduced the concept of a rate limit for requests that include the `additional-fields` or `include` parameters in the request. If you're making calls with either of these parameters, we will enforce a stricter rate limit on those requests. For example: If you're making an HTTP GET request to `/api/profiles?additional-fields[profile]=predictive_analytics`, your requests will be at a lower rate limit than if you had not requested that information. Similarly, a `GET` request to `/api/profiles/:profile-id:?include=lists` will result in a lower rate limit than a call to `/api/profiles/:profile-id:` without the query parameter. These changes are enforced at a global level. A request to `/api/segments/:segment-id:/profiles?additional-fields[profile]=predictive_analytics` will hit the same lower rate limit on profile->additional-fields->predictive_analytics as the call to `/api/profiles?additional-fields[profile]=predictive_analytics`. Note that each call now has multiple rate limits that apply. For example, let's assume we have 150 calls per minute on /api/profiles, 50 calls per minute on `additional-fields[profile]=predictive_analytics`, and 50 calls per minute on `/api/profiles/:profile-id:?include=lists`. We then make the following API calls: GET `/api/profiles/:profile-id:` – here, we use 1 call on the GET Profile endpoint GET `/api/profiles/:profile-id:?include=lists` – we use 1 call on the GET Profile endpoint and another call on `profile?include=lists` GET `/api/profiles/:profile-id:?include=lists&additional-fields[profile]=predictive_analytics` – three calls At the end of these three API calls, we now have: 147 calls remaining on `/api/profiles/:profile-id`: 48 calls remaining on `profiles?include=lists` 49 calls remaining on `additional-fields[profile]=predictive_analytics` The rate limits on all of these calls reset at the same window. Similar rules apply for burst limits. ## Ingestion limits > [!NOTE] > **Global payload limit** > We enforce a maximum total payload size of 5 MB (decompressed) for all of our new APIs. **Endpoints with additional limits:** - `/api/events` - `/client/events` - legacy `/api/track` Klaviyo's event tracking endpoints use ingestion limits to prevent processing delays and service interruptions to the event ingestion pipeline. If you are using a Klaviyo webhook, custom integration, or API implementation, it is important to be aware of the limits on the events you send into Klaviyo. The table below provides some guidance on the maximum sizes for your Events payload and its fields. | Category | Limit | | :--------------------------------------------- | :---------------------------- | | Max number of event properties per data packet | 400 | | Max size of any field | 100 kB | | Max number of items in arrays | 4000 | | Max levels of nested objects | 11 | | Timestamp of events | Between 1990 and “now”+1 year | ## Response status codes Our API uses conventional HTTP response status codes to indicate success or failure of an API request. Response status codes typically fall into the following three ranges: - 2xx - Success - 4xx - Error as a result of information provided as part of the request, such as a requested object that doesn't exist, an invalid setting, etc. - 5xx - Error due to server issues or service unavailability. See the table below for a list of error codes and their corresponding descriptions: | Code | Summary | Description | | --- | --- | --- | | 200 | OK | The request completed successfully. | | 201 | Created | The request succeeded, and a new resource was created as a result. | | 202 | Accepted | The request has been received but not yet acted upon. We return this status code for requests that were accepted but are processed asynchronously. | | 204 | No Content | The request succeeded, but the API doesn’t provide a response body. | | 400 | Bad Request | Request is missing a required parameter or has an invalid parameter. | | 401 | Not Authorized | Request is lacking required authentication information.
Please follow [the guidance here](https://developers.klaviyo.com/en/reference.md) for more details on authenticating your API requests. | | 403 | Forbidden | The request contains valid authentication information, but does not have permissions to perform the specified action.
See [API key scopes](https://developers.klaviyo.com/en/reference.md) for more information. | | 404 | Not Found | The requested resource doesn't exist. | | 405 | Method not Allowed | The requested resource doesn't support the provided HTTP method, e.g. `DELETE`. | | 409 | Conflict | The request conflicts with the current state of the server. | | 410 | Gone | The requested content has been permanently deleted from Klaviyo’s server. This status code will occur for requested endpoints that no longer exist in our API. | | 415 | Unsupported Media Type | The `Content-Type` or `Content-Encoding` header is set incorrectly. | | 429 | Rate Limit | You hit the rate limit for this endpoint (different endpoints have different rate limits). | | 500 | Server Error | Something is wrong with the destination server. This may be on Klaviyo's end. | | 503 | Service Unavailable | Something is wrong on Klaviyo’s end leading to service unavailability.
Check Klaviyo’s Status for updates. | ## Retries We recommend watching for 429 and 503 error codes and building in a retry mechanism. The retry mechanism should follow an [exponential backoff](https://en.wikipedia.org/wiki/Exponential_backoff) schedule to reduce request volume when necessary. Be sure to build in some randomness into the backoff schedule to avoid a [thundering herd effect](https://en.wikipedia.org/wiki/Thundering_herd_problem). > [!WARNING] > A retry should only be attempted after the current rate limit is lifted, i.e., the time (in seconds) indicated by the `Retry-After` header on a 429 response has expired. Immediate retries will always receive a 429 error. ## Errors When a request is unsuccessful, the response will include a list of errors, nested under an `errors` field in the response. Within the `error` object, the `title` field includes developer-facing information about why the request failed. Here is an example of an error response returned for an invalid request to GET `/api/events?fields[profile]=email&include=profiless` with an invalid `include` query parameter provided. There’s a typo there! It should be `include=profiles` not `include=profiless`. ```json { "errors": [ { "id": "2c76424d-b1ff-4afd-a2a1-728d85dac775", "status": 400, "code": "invalid", "title": "Invalid input.", "detail": "'profiless' is not an allowed include parameter for this resource.", "source": { "parameter": "include" }, "meta": {} } ] } ``` --- # Filtering > This is the Markdown version of https://developers.klaviyo.com/en/docs/filtering_ Learn how to use our JSON:API filtering syntax. ## Filter syntax Our JSON:API general filtering syntax and its supported operations can be used across our new APIs. Please note that support for given operators and fields is highly specific to each endpoint. You can refer to the `filter` query parameter in the API reference documentation for which operators are supported for each field. The filtering syntax for Klaviyo’s new APIs uses the `?filter` query parameter for all endpoints that support filter operations. The following filter syntax can be used for more complex filtering operations across all endpoints: ![Diagram of filter syntax showing reserved keyword, operation function, field name, and arguments ](https://files.readme.io/9726e83-image.png) ### URI encoding Filter expressions can contain non-URL-safe characters. We recommend that you always URI-encode the value of the filter query parameter to ensure your filter expression functions properly. See [the MDN docs on encodeURIComponent](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent) for more details. ## Filter operations ### Filter operators Below are the filter operators supported by our filter syntax. The documentation for each endpoint will indicate on the `filter` field which fields are enabled for filtering and which filter operators they support. | Operator | Description | Supported field types | Raw example | Encoded example | | ------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | | `equals` | Return all resources where specified field _equals_ provided value | string, boolean, number, datetime, array | `?filter=equals(email,"sarah.mason@klaviyo-demo.com")` | `?filter=equals(email%2C%22sarah.mason%40klaviyo-demo.com%22)` | | `less-than` | Return all resources where the specified field is _less than_ the provided value. | number, datetime | `?filter=less-than(datetime,2023-03-01T00:00:00Z)` | `?filter=less-than(datetime%2C2023-03-01T00%3A00%3A00Z)` | | `less-or-equal` | Return all resources where the specified field is _less than or equal to_ the provided value. | number, datetime | `?filter=less-or-equal(datetime,2023-03-01T00:00:00Z)` | `?filter=less-or-equal(datetime%2C2023-03-01T00%3A00%3A00Z)` | | `greater-than` | Return all resources where the specified field is _greater than_ the provided value. | number, datetime | `?filter=greater-than(datetime,2023-03-01T01:00:00Z)` | `?filter=greater-than(datetime%2C2023-03-01T00%3A00%3A00Z)` | | `greater-or-equal` | Return all resources where the specified field is _greater than or equal to_ the provided value. | number, datetime | `?filter=greater-or-equal(datetime,2023-03-01T00:00:00Z)` | `?filter=greater-or-equal(datetime%2C2023-03-01T00%3A00%3A00Z)` | | `contains` | Return all resources where the specified field "contains" the provided value, i.e. it is contained within a portion of a string or it is equal to an item within an array. | string, array | `?filter=contains(name,"marketing")` | `?filter=contains(name%2C%22marketing%22)` | | `contains-any` | Return all resources where the specified field contains _any_ of the items in the provided array value. | string, array | `?filter=contains-any(description,["sms","email"])` | `?filter=contains-any(description%2C%5B%22sms%22%2C%22email%22%5D)` | | `contains-all` | Return all resources where the specified field contains _all_ of the items in the provided array value. | string, array | `?filter=contains-all(description,["sms","email"])` | `?filter=contains-all(description%2C%5B%22sms%22%2C%22email%22%5D)` | | `ends-with` | Return all resources where the specified field ends with the provided value. | string | `?filter=ends-with(description,"End")` | `?filter=ends-with(description%2C%22End%22)` | | `starts-with` | Return all resources where the specified field starts with the provided value. | string | `?filter=starts-with(description,"Start")` | `?filter=starts-with(description%2C%22Start%22)` | | `any` | Return all resources where the specified field is _equal to any_ of the items in the provided array value. | string, number, datetime, boolean | `?filter=any(email,["sarah.mason@klaviyo-demo.com","matt-kemp@klaviyo-demo.com","lindsey.smith@klaviyo-demo.com"])` | `?filter=any(email%2C%5B%22sarah.mason%40klaviyo-demo.com%22%2C%22matt-kemp%40klaviyo-demo.com%22%2C%22lindsey.smith%40klaviyo-demo.com%22%5D)` | | `has` | Return all resources that have the specified resource. | object | `?filter=has(profile)` | `?filter=has%28profile%29&page%5Bcursor%5D=WzE3MDc1MjMyMTMsICI0WFVjeHIyV0pVUiIsIHRydWVd` | ### Boolean logic operators | Operator | Description | Raw example | Encoded example | | :------- | :------------------------------------------------------------------------------------------------ | :----------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------- | | `and` | This operator accepts other operator functions as arguments to perform a logical `AND` operation. | `?filter=and(equals(first_name,"Jane"),equals(email,"jane@klaviyo-demo.com"))` | `?filter=and(equals(first_name%2C%22Jane%22)%2Cequals(email%2C%22jane%40klaviyo-demo.com%22))` | | `,` | This can be used to perform an implicit `AND` operation. | `?filter=equals(first_name,"Jane"),equals(email,"jane@klaviyo-demo.com")` | `?filter=equals(first_name%2C%22Jane%22)%2Cequals(email%2C%22jane%40klaviyo-demo.com%22)` | > [!NOTE] > **Klaviyo’s APIs also interpret comma-separated filter expressions as an alias for an `and` wrapper function.** > For example: `filter=and(equals(field1,"foo"),equals(field2,"bar"))` > can be simplified to > `filter=equals(field1,"foo"),equals(field2,"bar")` > > This can be particularly helpful for filtering on a date range. For example, pulling all events for a specific metric for a specific time range would look like the below, swapping out your own metric_id and datetime values: > > `filter=equals(metric_id,"UxxK4u"),greater-or-equal(datetime,2023-02-07),less-than(datetime,2023-02-15)` ## Comparison literals - `string`: Arguments representing string literals are expressed with quotation marks (we will accept either single quoted or double-quoted strings). Single or double-quoted characters within strings (quoted with like quote characters) MUST be escaped with a single backslash (i.e. ‘Tony\\’s ball’) Comparisons to all string literals are case-sensitive, unless otherwise noted in endpoint specific documentation - `boolean`: Booleans are expressed as unquoted true and false literal values - `number`: Numbers are expressed as standard integer or float representations - `datetime`: Datetimes are expressed as unquoted ISO-8601 RFC-3339 formatted strings. For example, `2012-04-21T11:30:00-04:00` - `array`: Array literals are expressed using square brackets ([ ]) - `null`: `null` is a reserved literal to represent null values for fields of any type --- # Sorting > This is the Markdown version of https://developers.klaviyo.com/en/docs/sorting_ Klaviyo Developers | Learn how to use our JSON:API sorting feature. ## Sort syntax Klaviyo’s JSON:API sorting syntax can be used across all supported endpoints in our new APIs. Please note that support for given fields is unique to each endpoint. Refer to the `sort` query parameter in the API reference documentation. For endpoints that support sort operations, you can set `sort` to a field name in the response body such as `datetime`, for example. The sorting direction can be ascending (default) or descending. The following example shows how to retrieve a sorted list of events by `datetime` in ascending order (oldest to newest): ```curl Request curl --request GET \ --url 'https://a.klaviyo.com/api/events/?sort=datetime' \ --header 'Authorization: Klaviyo-API-Key your-private-api-key' \ --header 'accept: application/json' \ --header 'revision: 2023-07-15' ``` ```json Response { "data": [ { "type": "event", "id": "4sDShKQjrdT", "attributes": { "timestamp": 1690229757, "event_properties": { "Carrier Delivery Status": "delivered", "extra": { "Message Body": "Klaviyo Sample Data: This is an example SMS received message body.", "Message ID": "01H64RPNNC42DZNR9EHDGPWTSH" }, "From Number": "+15005550006", "From Phone Region": "US", "Message Format": "SMS", "Message Name": "Internal Klaviyo - Test Campaign Name", "Message Type": "campaign", "Segment Count": 1, "To Number": "55896", "To Phone Region": "US", "$event_id": "sample_data_gen:1665417e-c31a-42dd-a444-04d5edb48b3e" }, "datetime": "2023-07-24 20:15:57+00:00", "uuid": "e60d7c80-2a5e-11ee-8001-c1ee7c948be0" }, "relationships": { "profile": { "data": { "type": "profile", "id": "01H64RPM2KR4VDGBWQHFVT6032" }, "links": { "self": "https://a.klaviyo.com/api/events/4sDShKQjrdT/relationships/profile/", "related": "https://a.klaviyo.com/api/events/4sDShKQjrdT/profile/" } }, "metric": { "data": { "type": "metric", "id": "WwY7Gb" }, "links": { "self": "https://a.klaviyo.com/api/events/4sDShKQjrdT/relationships/metric/", "related": "https://a.klaviyo.com/api/events/4sDShKQjrdT/metric/" } } }, "links": { "self": "https://a.klaviyo.com/api/events/4sDShKQjrdT/" } }, { "type": "event", "id": "4vGfpcpPRGL", "attributes": { "timestamp": 1692028246, "event_properties": { "custom_value": "newer event time value", "$event_id": "YjpZcE" }, "datetime": "2023-08-14 15:50:46+00:00", "uuid": "55084f00-3aba-11ee-8001-a3e96a3d92dc" }, "relationships": { "profile": { "data": { "type": "profile", "id": "01H7TBW70G8RYXHF9D91K4W72J" }, "links": { "self": "https://a.klaviyo.com/api/events/4vGfpcpPRGL/relationships/profile/", "related": "https://a.klaviyo.com/api/events/4vGfpcpPRGL/profile/" } }, "metric": { "data": { "type": "metric", "id": "TQpx2b" }, "links": { "self": "https://a.klaviyo.com/api/events/4vGfpcpPRGL/relationships/metric/", "related": "https://a.klaviyo.com/api/events/4vGfpcpPRGL/metric/" } } }, "links": { "self": "https://a.klaviyo.com/api/events/4vGfpcpPRGL/" } } ], "links": { "self": "https://a.klaviyo.com/api/events/?sort=datetime", "next": null, "prev": null } } ``` You can retrieve events by `datetime` in descending order (newest to oldest) by using a `-` prefix as shown below: ```curl Request curl --request GET \ --url 'https://a.klaviyo.com/api/events/?filter=profile&sort=-datetime' \ --header 'Authorization: Klaviyo-API-Key your-private-api-key' \ --header 'accept: application/json' \ --header 'revision: 2023-07-15' ``` ```json Response { "data": [ { "type": "event", "id": "4vGfpcpPRGL", "attributes": { "timestamp": 1692028246, "event_properties": { "custom_value": "newer event time value", "$event_id": "YjpZcE" }, "datetime": "2023-08-14 15:50:46+00:00", "uuid": "55084f00-3aba-11ee-8001-a3e96a3d92dc" }, "relationships": { "profile": { "data": { "type": "profile", "id": "01H7TBW70G8RYXHF9D91K4W72J" }, "links": { "self": "https://a.klaviyo.com/api/events/4vGfpcpPRGL/relationships/profile/", "related": "https://a.klaviyo.com/api/events/4vGfpcpPRGL/profile/" } }, "metric": { "data": { "type": "metric", "id": "TQpx2b" }, "links": { "self": "https://a.klaviyo.com/api/events/4vGfpcpPRGL/relationships/metric/", "related": "https://a.klaviyo.com/api/events/4vGfpcpPRGL/metric/" } } }, "links": { "self": "https://a.klaviyo.com/api/events/4vGfpcpPRGL/" } }, { "type": "event", "id": "4sDShKQjrdT", "attributes": { "timestamp": 1690229757, "event_properties": { "Carrier Delivery Status": "delivered", "extra": { "Message Body": "Klaviyo Sample Data: This is an example SMS received message body.", "Message ID": "01H64RPNNC42DZNR9EHDGPWTSH" }, "From Number": "+15005550006", "From Phone Region": "US", "Message Format": "SMS", "Message Name": "Internal Klaviyo - Test Campaign Name", "Message Type": "campaign", "Segment Count": 1, "To Number": "55896", "To Phone Region": "US", "$event_id": "sample_data_gen:1665417e-c31a-42dd-a444-04d5edb48b3e" }, "datetime": "2023-07-24 20:15:57+00:00", "uuid": "e60d7c80-2a5e-11ee-8001-c1ee7c948be0" }, "relationships": { "profile": { "data": { "type": "profile", "id": "01H64RPM2KR4VDGBWQHFVT6032" }, "links": { "self": "https://a.klaviyo.com/api/events/4sDShKQjrdT/relationships/profile/", "related": "https://a.klaviyo.com/api/events/4sDShKQjrdT/profile/" } }, "metric": { "data": { "type": "metric", "id": "WwY7Gb" }, "links": { "self": "https://a.klaviyo.com/api/events/4sDShKQjrdT/relationships/metric/", "related": "https://a.klaviyo.com/api/events/4sDShKQjrdT/metric/" } } }, "links": { "self": "https://a.klaviyo.com/api/events/4sDShKQjrdT/" } } ], "links": { "self": "https://a.klaviyo.com/api/events/?sort=-datetime", "next": null, "prev": null } } ``` ## Example request and response In the following example, we make a request to get email campaigns and sort them in descending order (oldest to newest) with the `created_at` field: ```curl Request curl --request GET \ --url 'https://a.klaviyo.com/api/campaigns/?filter=equals(messages.channel,’email’)&sort=created_at' \ --header 'Authorization: Klaviyo-API-Key your-private-api-key' \ --header 'accept: application/json' \ --header 'revision: 2023-07-15' ``` ```json Response { "data": [ { "type": "campaign", "id": "01H64RPN6K46BFY3G87KB742ZK", "attributes": { "name": "Internal Klaviyo - Test Campaign Name", "status": "Sent", "archived": false, "audiences": { "included": [ "VKT4tu" ], "excluded": [] }, "send_options": { "use_smart_sending": false, "ignore_unsubscribes": false }, "tracking_options": { "is_add_utm": false, "utm_params": [], "is_tracking_clicks": true, "is_tracking_opens": true }, "send_strategy": { "method": "immediate", "options_static": null, "options_throttled": null, "options_sto": null }, "created_at": "2023-07-24T20:15:57.149220+00:00", "scheduled_at": null, "updated_at": "2023-07-24T20:15:57.149249+00:00", "send_time": null }, "relationships": { "campaign-messages": { "data": [ { "type": "campaign-message", "id": "01H64RPN72SBJ2MC2BYCZ23QMY" } ], "links": { "self": "https://a.klaviyo.com/api/campaigns/01H64RPN6K46BFY3G87KB742ZK/relationships/campaign-messages/", "related": "https://a.klaviyo.com/api/campaigns/01H64RPN6K46BFY3G87KB742ZK/campaign-messages/" } }, "tags": { "links": { "self": "https://a.klaviyo.com/api/campaigns/01H64RPN6K46BFY3G87KB742ZK/relationships/tags/", "related": "https://a.klaviyo.com/api/campaigns/01H64RPN6K46BFY3G87KB742ZK/tags/" } } }, "links": { "self": "https://a.klaviyo.com/api/campaigns/01H64RPN6K46BFY3G87KB742ZK/" } }, { "type": "campaign", "id": "01H7AZ0HEP1E6J65B0M0AM5N7D", "attributes": { "name": "August 8 Test Campaign", "status": "Draft", "archived": false, "audiences": { "included": [ "Seu3Hc" ], "excluded": [] }, "send_options": { "use_smart_sending": false, "ignore_unsubscribes": false }, "tracking_options": { "is_add_utm": false, "utm_params": [], "is_tracking_clicks": true, "is_tracking_opens": true }, "send_strategy": { "method": "static", "options_static": { "datetime": "2023-08-08T04:00:00+00:00", "is_local": false, "send_past_recipients_immediately": null }, "options_throttled": null, "options_sto": null }, "created_at": "2023-08-08T16:17:20.863711+00:00", "scheduled_at": null, "updated_at": "2023-08-08T16:19:53.275045+00:00", "send_time": null }, "relationships": { "campaign-messages": { "data": [ { "type": "campaign-message", "id": "01H7AZ0HF35HBTCAQXNR55TKTT" } ], "links": { "self": "https://a.klaviyo.com/api/campaigns/01H7AZ0HEP1E6J65B0M0AM5N7D/relationships/campaign-messages/", "related": "https://a.klaviyo.com/api/campaigns/01H7AZ0HEP1E6J65B0M0AM5N7D/campaign-messages/" } }, "tags": { "links": { "self": "https://a.klaviyo.com/api/campaigns/01H7AZ0HEP1E6J65B0M0AM5N7D/relationships/tags/", "related": "https://a.klaviyo.com/api/campaigns/01H7AZ0HEP1E6J65B0M0AM5N7D/tags/" } } }, "links": { "self": "https://a.klaviyo.com/api/campaigns/01H7AZ0HEP1E6J65B0M0AM5N7D/" } } ], "links": { "self": "https://a.klaviyo.com/api/campaigns/?filter=equals(messages.channel,%27email%27)&sort=created_at", "next": null, "prev": null } } ``` > [!WARNING] > Sorting by multiple fields is not supported. ## SDK example (Node, PHP, Python, Ruby) This example shows how to sort events by `datetime` with Klaviyo’s SDKs: ```javascript Node import { ConfigWrapper, EventsApi } from 'klaviyo-api' const eventsApi = new EventsApi(ConfigWrapper("")) const events = await eventsApi.getEvents({sort: '-datetime'}) ``` ```php PHP $klaviyo->Events->getEvents( $fields_event=['event_properties'], $fields_metric=NULL, $fields_profile=NULL, $filter="equals(metric_id,\"UMTLbD\")", $include=NULL, $page_cursor=NULL, $sort='-datetime' ); ``` ```python Python klaviyo.Events.get_events( fields_event=['event_properties'], filter="equals(metric_id,\"aBc123\")", sort='-datetime' ) ``` ```ruby Ruby opts = { sort: '-datetime' } response = KlaviyoAPI::Events.get_events(opts) ``` ## Additional resources - Export data from Klaviyo - Custom integration FAQs --- # Sparse fieldsets > This is the Markdown version of https://developers.klaviyo.com/en/docs/sparse_fieldsets Learn how to request specific fields from resources. Sparse fieldsets allow you to request only specific fields from a resource or collection. Note that support for this functionality is endpoint-specific. Refer to the `fields` query parameter in our API reference documentation. ## Sparse fieldsets syntax Sparse fieldsets are specified using `?fields[TYPE]=field1,field2` as a query parameter, where `TYPE` is the singular resource type, e.g., `profile`, from which to select only `field1` and `field2.` > [!WARNING] > The specified field(s) must be in a comma-separated list. Watch out for whitespaces before or after each comma. ## Example request and response A request to Get Catalogs Variants returns a considerable amount of data, including up to 15 different attributes per catalog variant. Large responses like these can lead to extra HTTP responses and data stored in memory. It’s likely you are only interested in a fraction of this data. Fortunately, this customization can be achieved with sparse fieldsets. The following request to Get Catalogs Variant uses sparse fieldsets to return only `external_id` and `title` attributes from each catalog variant in the response: ```curl Request curl --request GET \ --url 'https://a.klaviyo.com/api/catalog-variants/?fields%5Bcatalog-variant%5D=external_id,title' \ --header 'Authorization: Klaviyo-API-Key your-private-api-key' \ --header 'accept: application/json' \ --header 'revision: 2023-09-15' ``` ```json Response { "data": [ { "type": "catalog-variant", "id": "$custom:::$default:::SAMPLE-DATA-ITEM-1-VARIANT-MEDIUM", "attributes": { "external_id": "SAMPLE-DATA-ITEM-1-VARIANT-MEDIUM", "title": "Ocean Blue Shirt (Sample) Variant Medium" }, "relationships": { "item": { "links": { "self": "https://a.klaviyo.com/api/catalog-variants/$custom:::$default:::SAMPLE-DATA-ITEM-1-VARIANT-MEDIUM/relationships/item/", "related": "https://a.klaviyo.com/api/catalog-variants/$custom:::$default:::SAMPLE-DATA-ITEM-1-VARIANT-MEDIUM/item/" } } }, "links": { "self": "https://a.klaviyo.com/api/catalog-variants/$custom:::$default:::SAMPLE-DATA-ITEM-1-VARIANT-MEDIUM/" } }, { "type": "catalog-variant", "id": "$custom:::$default:::SAMPLE-DATA-ITEM-1-VARIANT-LARGE", "attributes": { "external_id": "SAMPLE-DATA-ITEM-1-VARIANT-LARGE", "title": "Ocean Blue Shirt (Sample) Variant Large" }, "relationships": { "item": { "links": { "self": "https://a.klaviyo.com/api/catalog-variants/$custom:::$default:::SAMPLE-DATA-ITEM-1-VARIANT-LARGE/relationships/item/", "related": "https://a.klaviyo.com/api/catalog-variants/$custom:::$default:::SAMPLE-DATA-ITEM-1-VARIANT-LARGE/item/" } } }, "links": { "self": "https://a.klaviyo.com/api/catalog-variants/$custom:::$default:::SAMPLE-DATA-ITEM-1-VARIANT-LARGE/" } } ], "links": { "self": "https://a.klaviyo.com/api/catalog-variants?fields[catalog-variant]=external_id,title", "next": null, "prev": null } } ``` Note that the `relationships` and `links` fields are still fully populated in the response. Each `attribute` object only contains the `external_id` and `title` fields as requested. ### Sparse fieldsets with included resource types You can specify sparse fieldsets for included resource types. For example, you might want to retrieve profile email addresses linked to a list of events. To do this, you must use the `include` query parameter to include the `profile` resource. Then, you can set `profile` as the resource type and `email` as a field as shown in the example below: ```curl Request curl --request GET \ --url 'https://a.klaviyo.com/api/events?include=profile&fields%5Bprofile%5D=email' \ --header 'Authorization: Klaviyo-API-Key your-private-api-key' \ --header 'accept: application/json' \ --header 'revision: 2023-09-15' ``` ```json Response { "data": [ { "type": "event", "id": "4v7eCFTjDyX", "attributes": { "timestamp": 1691679684, "event_properties": { "browser": "Firefox", "os": "Windows", "page": "http://www.example.com/landing", "$event_id": "sample_data_gen:b80a551a-061e-42d1-8890-432006b54c8b" }, "datetime": "2023-08-10 15:01:24+00:00", "uuid": "c5e3fa00-378e-11ee-8001-08175e8dffb7" }, "relationships": { "profile": { "data": { "type": "profile", "id": "01H7FZEVHAZB1TNK8KBVGE0YZR" }, "links": { "self": "https://a.klaviyo.com/api/events/4v7eCFTjDyX/relationships/profile/", "related": "https://a.klaviyo.com/api/events/4v7eCFTjDyX/profile/" } }, "metric": { "data": { "type": "metric", "id": "XWCLtq" }, "links": { "self": "https://a.klaviyo.com/api/events/4v7eCFTjDyX/relationships/metric/", "related": "https://a.klaviyo.com/api/events/4v7eCFTjDyX/metric/" } } }, "links": { "self": "https://a.klaviyo.com/api/events/4v7eCFTjDyX/" } }, ... ], "included": [ { "type": "profile", "id": "01H7FZEVHAZB1TNK8KBVGE0YZR", "attributes": { "email": "lindsey.smith@klaviyo-demo.com" }, "relationships": { "lists": { "links": { "self": "https://a.klaviyo.com/api/profiles/01H7FZEVHAZB1TNK8KBVGE0YZR/relationships/lists/", "related": "https://a.klaviyo.com/api/profiles/01H7FZEVHAZB1TNK8KBVGE0YZR/lists/" } }, "segments": { "links": { "self": "https://a.klaviyo.com/api/profiles/01H7FZEVHAZB1TNK8KBVGE0YZR/relationships/segments/", "related": "https://a.klaviyo.com/api/profiles/01H7FZEVHAZB1TNK8KBVGE0YZR/segments/" } } }, "links": { "self": "https://a.klaviyo.com/api/profiles/01H7FZEVHAZB1TNK8KBVGE0YZR/" } }, ... ], "links": { "self": "https://a.klaviyo.com/api/events?include=profile&fields[profile]=email", "next": null, "prev": null } } ``` Note that the `included `field of the response payload contains a list of profiles with its `attributes` limited to the `email` field as requested. > [!WARNING] > Note that sparse fieldsets can only be used on fields that exist across a resource. For example, across the event resource, you can use sparse fieldsets to only return the `event_properties` field. However, you cannot use sparse fieldsets to only return specific fields within the `event_properties` field itself. ## Additional fields You can use ?`additional-fields` as a query parameter to return additional fields not shown by default in the response body. This query parameter shares the same syntax as sparse fieldsets, i.e., `?additional-fields[TYPE]=field,` where `TYPE` is the singular resource type, e.g., `profile`, and `field` is the additional field. Support for `additional-fields` is endpoint-specific. ### Example request and response The following request to Get List uses the `?additional-fields` query parameter to return `profile_count`, a field representing the number of profiles on a given list: ```curl Request curl --request GET \ --url 'https://a.klaviyo.com/api/lists/RB89mt/?additional-fields%5Blist%5D=profile_count' \ --header 'Authorization: Klaviyo-API-Key your-private-api-key' \ --header 'accept: application/json' \ --header 'revision: 2023-09-15' ``` ```json Response { "data": { "type": "list", "id": "RB89mt", "attributes": { "name": "Profile List", "created": "2023-06-05T14:49:54+00:00", "updated": "2023-06-06T14:20:50+00:00", "profile_count": 10 }, "relationships": { "profiles": { "links": { "self": "https://a.klaviyo.com/api/lists/RB89mt/relationships/profiles/", "related": "https://a.klaviyo.com/api/lists/RB89mt/profiles/" } }, "tags": { "links": { "self": "https://a.klaviyo.com/api/lists/RB89mt/relationships/tags/", "related": "https://a.klaviyo.com/api/lists/RB89mt/tags/" } } }, "links": { "self": "https://a.klaviyo.com/api/lists/RB89mt/" } } } ``` ### Predictive analytics The `?additional-fields` parameter allows you to retrieve predictive analytics via API, which are valuable for monitoring metrics such as customer lifetime value (CLV) and order predictions for profiles. > [!NOTE] > To be eligible for predictive analytics, your account must meet the following conditions: > > - At least 500 customers have placed an order. > - You have an ecommerce integration or use our API to send placed orders. > - You have at least 180 days of order history, including orders within the last 30 days. > - You have customers who have placed 3 or more orders. > > Learn more about [Klaviyo's predictive analytics](https://help.klaviyo.com/hc/en-us/articles/360020919731). The full list of predictive analytics fields that can be returned for a profile are: | Field | Description | | :---------------------------- | :------------------------------------------------------------------------------ | | `historic_clv` | Total value of all historically placed orders. | | `predicted_clv` | Predicted value of all placed orders in the next 365 days. | | `total_clv` | Sum of historic and predicted CLV. | | `historic_number_of_orders` | Number of placed orders. | | `predicted_number_of_orders` | Predicted number of placed orders in the next 365 days. | | `average_days_between_orders` | Average number of days between orders, over all time. | | `average_order_value` | Average value of historically placed orders. | | `churn_probability` | Probability that the customer will never make another purchase, or churn. | | `expected_date_of_next_order` | Expected date of next order, calculated at the time of their most recent order. | | `ranked_channel_affinity` | Lists the profile's subscribed channels from most-preferred to least, for example, `["sms", "email", "push"]`. If a profile is not subscribed to any channels, this field has a value of `None`. | > [!NOTE] > You can use sparse fieldsets to request for only a field(s) not included by default in the response. For example, you can request for additional fields with sparse fieldsets to include only `predictive_analytics` in the response. Be sure to use both query parameters in your request. ## SDK example (Node, PHP, Python, Ruby) This SDK example shows how to request events along with their related profile attributes limited to `external_id` and `title `fields: ```javascript Node import { ConfigWrapper, Events } from 'klaviyo-api'; ConfigWrapper(process.env["KLAVIYO_PRIVATE_API_KEY"])); const eventsList = await Events.getEvents({fieldsProfile:["external_id","title"],include:["profile"]}); ``` ```php PHP $klaviyo->Events->getEvents( $fields_event=NULL, $fields_metric=NULL, $fields_profile=['external_id','title'], $include=['profile'], $page_cursor=NULL ); ``` ```python Python klaviyo.Events.get_events( fields_profile=['external_id','title'], include=['profile'] ) ``` ```ruby Ruby opts = { fields_profile: ["external_id","title"], include: ['profile'] } response = KlaviyoAPI::Events.get_events(opts) ``` ## Additional resources - JSON:API relationships guide - Comparison between v1/v2 and new APIs --- # Relationships > This is the Markdown version of https://developers.klaviyo.com/en/docs/relationships_ Learn more about resource relationships available with the JSON:API standard. ## What are relationships? Klaviyo’s modern APIs offer powerful new functionality via the `relationships` object, a thorough set of syntax offered by JSON:API for modeling relationships between resources. This syntax allows developers to efficiently query specific groups of related resources, eliminating the need to perform redundant queries. Relationships can be to-one or to-many. Because of the myriad ways our partners and customers model and sync data to and from Klaviyo, the JSON:API relationship syntax used by the new APIs accounts for a wide variety of use cases. Keep in mind that a full relationship mapping may not always be required for all resources. ## The `include` query parameter You can use `?include=resource1,resource2` as a query parameter to include related resource(s) in a response. For example, a call to [Get Event](https://developers.klaviyo.com/en/reference/get_event.md) with `?include=profile,metric` will include related profile and metric data for each event in the response. To determine which relationships a specific resource supports, refer to the endpoint’s supported `include` values in the endpoint description. > [!WARNING] > The specified resources must be in a comma-separated list. You cannot use `?include` more than once in your request, i.e, `?include=resource1&include=resource2`. Use `?include=resource1,resource2` for including multiple related resources. Watch out for whitespaces before or after each comma. Note that `include` values may be singular or plural depending on the relationship between resources: - **Singular (to-one)** `GET /api/events/?include=profile` Includes each profile related to each event. - **Plural (to-many)** `GET /api/profiles/{profile_id}/?include=lists` Includes lists related to a single profile. ### Example request and response In the example request to [Get Profile](https://developers.klaviyo.com/en/reference/get_profile.md) below, `?include=lists,segments` returns any related list and/or segment object(s) related to a specific profile in the `included` field of the response: ```curl Request curl --request GET \ --url 'https://a.klaviyo.com/api/profiles/01HD2CCW560NWG693CYF6KF28S/?include=lists,segments' \ --header 'Authorization: Klaviyo-API-Key your-private-api-key' \ --header 'accept: application/json' \ --header 'revision: 2023-10-15' ``` ```json Response { "data": { "type": "profile", "id": "01HD2CCW560NWG693CYF6KF28S", "attributes": { "email": "john.appleseed@example.com", "first_name": "John", "last_name": "Appleseed", "created": "2023-10-18T21:52:18+00:00", "updated": "2023-10-19T14:03:29+00:00" }, "relationships": { "lists": { "data": [ { "type": "list", "id": "TE8Gur" } ], "links": { "self": "https://a.klaviyo.com/api/profiles/01HD2CCW560NWG693CYF6KF28S/relationships/lists/", "related": "https://a.klaviyo.com/api/profiles/01HD2CCW560NWG693CYF6KF28S/lists/" } }, "segments": { "data": [ { "type": "segment", "id": "Wu2ui7" } ], "links": { "self": "https://a.klaviyo.com/api/profiles/01HD2CCW560NWG693CYF6KF28S/relationships/segments/", "related": "https://a.klaviyo.com/api/profiles/01HD2CCW560NWG693CYF6KF28S/segments/" } } }, "links": { "self": "https://a.klaviyo.com/api/profiles/01HD2CCW560NWG693CYF6KF28S/" } }, "included": [ { "type": "list", "id": "TE8Gur", "attributes": { "name": "Newsletter", "created": "2023-08-10T14:59:46+00:00", "updated": "2023-08-10T14:59:46+00:00" }, "relationships": { "profiles": { "links": { "self": "https://a.klaviyo.com/api/lists/TE8Gur/relationships/profiles/", "related": "https://a.klaviyo.com/api/lists/TE8Gur/profiles/" } }, "tags": { "links": { "self": "https://a.klaviyo.com/api/lists/TE8Gur/relationships/tags/", "related": "https://a.klaviyo.com/api/lists/TE8Gur/tags/" } } }, "links": { "self": "https://a.klaviyo.com/api/lists/TE8Gur/" } }, { "type": "segment", "id": "Wu2ui7", "attributes": { "name": "Loyal Customers", "created": "2023-10-19T20:03:28+00:00", "updated": "2023-10-19T20:04:09+00:00" }, "relationships": { "profiles": { "links": { "self": "https://a.klaviyo.com/api/segments/Wu2ui7/relationships/profiles/", "related": "https://a.klaviyo.com/api/segments/Wu2ui7/profiles/" } }, "tags": { "links": { "self": "https://a.klaviyo.com/api/segments/Wu2ui7/relationships/tags/", "related": "https://a.klaviyo.com/api/segments/Wu2ui7/tags/" } } }, "links": { "self": "https://a.klaviyo.com/api/segments/Wu2ui7/" } } ] } ``` ## Scopes When using relationships, you must use an API key with Read-only (for GET requests) or Full (for GET and POST requests) permissions to both the requested endpoint and its related resource. For example, to call `GET /api/profiles/{profile_id}/?include=lists` the scope of your API key must include read access to both the profiles endpoint and the lists endpoint. Check out the guide to API scopes to learn more about creating and using scopes. ## Relationship support When a relationship between two resources is defined, there are two main ways of querying this relationship: single source and collection-level. ### Single resource relationship support Let's use `/profiles` and `/lists` as an example. A common use case for many Klaviyo developers is getting all lists a profile belongs to. With the new APIs, this could be accomplished the following ways: - `GET /api/profiles/{profile_id}/lists` Get the lists for a single profile directly. Do this if you do not need the profile resource itself, you only need the list. - `GET /api/profiles/{profile_id}/?include=lists` Include the lists for a single profile. Do this if you need both the profile resource, and its corresponding lists. - `GET /api/profiles/{profile_id}/relationships/lists` Get just the relationship object (the ID mapping) to the corresponding list ID. Do this if you only need the list IDs for a profile's lists, and do not need either the profile resource or its corresponding lists. This is also the endpoint you can use to create, update or delete relationships, if these operations are supported for the relationship in question. #### Example request & response In this example, we have requested all lists related to the specified profile ID. This request returns the list resources only. ```curl Request curl --request GET \ --url 'https://a.klaviyo.com/api/profiles/{profile_id}/lists' \ --header 'Accept: application/json' --header 'Authorization: Klaviyo-API-Key {your-private-api-key}' --header 'Revision: YYYY-MM-DD.pre' ``` ```json Response { "data": [ { "type": "list", "id": "V7Raqa", "attributes": { "name": "Sample Data List", "created": "2022-06-15T16:01:12+00:00", "updated": "2022-06-15T16:01:12+00:00" }, "links": { "self": "https://a.klaviyo.com/api/lists/V7Raqa/" } } ], "links": { "self": "https://a.klaviyo.com/api/v3/profiles/01G5MDK0GX6K293W4647RNEGXB/lists/", "next": null, "prev": null } } ``` ### Collection-level relationship support Additionally, certain endpoints support `include` parameters for top-level `GET` endpoints. Refer to our API reference documentation for more information on which endpoints support `include` parameters. Use `include` if you need all resources from a particular endpoint (paginated) AND all of their corresponding resources from the relationship. #### Example request & response In this example, we have requested a specific event ID, and have included all profiles related to that event. ```curl Request curl --request GET \ --url 'https://a.klaviyo.com/api/events/{event-ID}/?include=profile' \ --header 'Accept: application/json' --header 'Authorization: Klaviyo-API-Key {your-private-api-key}' --header 'Revision: YYYY-MM-DD.pre' ``` ```json Response { "data": { "type": "event", "id": "3pAMewFCZAT", "attributes": { "metric_id": "PQ4zJA", "profile_id": "01G5MDK0GX6K293W4647RNEGXB", "timestamp": 1655321496, "event_properties": { "ProductName": "A Tale of Two Cities", "ProductID": "1112", "Categories": [ "Fiction", "Classics" ], "ImageURL": "http://www.example.com/path/to/product/image.png", "URL": "http://www.example.com/path/to/product", "Brand": "Harcourt Classics", "Price": 19.99, "CompareAtPrice": 19.99, "$event_id": "sample_data_gen:d3c56774-845a-43fa-a720-632c5e28901c" }, "datetime": "2022-06-15 19:31:36+00:00", "uuid": "c5161c00-ece1-11ec-8001-323081228ece" }, "relationships": { "profiles": { "data": [ { "type": "profiles", "id": "01G5MDK0GX6K293W4647RNEGXB" } ] } }, "links": { "self": "https://a.klaviyo.com/api/events/3pAMewFCZAT/" } }, "included": [ { "type": "profile", "id": "01G5MDK0GX6K293W4647RNEGXB", "attributes": { "email": "lindsey.smith@klaviyo-demo.com", "phone_number": null, "external_id": null, "anonymous_id": null, "first_name": "Lindsey", "last_name": "Smith (Sample)", "organization": "Klaviyo", "title": "engineer", "image": null, "created": "2022-06-15T19:31:34+00:00", "updated": "2022-06-15T19:31:36+00:00", "last_event_date": "2022-06-15T19:31:36+00:00", "location": { "address1": "302 W 3rd St", "address2": "Unit 600", "city": "Cincinnati", "country": "USA", "latitude": null, "longitude": null, "region": "OH", "zip": "45202", "timezone": null }, "properties": { "$latitude": "39.1031", "$longitude": "84.5120", "klaviyo_sample_data_gen": true } }, "links": { "self": "https://a.klaviyo.com/api/profiles/01G5MDK0GX6K293W4647RNEGXB/" } } ] } ``` ## Modify a relationship You can not only read relationships, you can also create and delete them. ### Create a relationship To create a new relationship between two resources, make a `POST` request to the endpoint with the relationship specified in the request body. In this example, we add a profile to a list by sending a POST to that profiles’ list relationship URL, specifying the list ID in the body. ```curl curl --request POST \ --url 'https://a.klaviyo.com/api/profiles/{profile_id}/relationships/lists' \ --header 'Accept: application/json' --header 'Authorization: Klaviyo-API-Key {your-private-api-key}' --header 'Revision: YYYY-MM-DD.pre' --data ' { "type": "list", "id": "{list_id}" } ’ ``` ### Delete a relationship To delete a relationship, make a `DELETE` request to the endpoint with the relationship specified in the request body. In this example, we are removing the relationship between a profile and the list ID defined in the request body. ```curl curl --request DELETE \ --url 'https://a.klaviyo.com/api/profiles/{profile_id}/relationships/lists' \ --header 'Accept: application/json' --header 'Authorization: Klaviyo-API-Key {your-private-api-key}' --header 'Revision: YYYY-MM-DD.pre' --data ' { "type": "list", "id": "{list_id}" } ’ ``` --- # Web and Mobile SDKs > This is the Markdown version of https://developers.klaviyo.com/en/docs/sdk_overview Klaviyo offers SDKs for server-side languages (Python, PHP, Ruby, Node) and mobile platforms (iOS, Android, React Native, Flutter). ## Server-side SDKs ### /api (Stable) - Node - PHP - Python - Ruby ## Mobile SDKs Klaviyo's mobile SDKs let you bring the full power of Klaviyo into your mobile app: - **Profile identification** — recognize your users - **Event tracking** — capture in-app behaviors and conversions - **Push notifications** — send targeted, personalized push messages - **In-app forms** — surface pop-up experiences without leaving the app - **Geofencing** — track real-world locations to trigger marketing content All these features are available for iOS, Android, React Native and Flutter apps through our respective SDKs. ### iOS - iOS Swift ### Android - Android ### React Native - React Native ### Expo - Expo Plugin ### Flutter - Flutter --- ## Deprecated Server-side SDKs > [!CAUTION] > **All v1/v2 SDKs were retired on June 30, 2024 and will not receive further updates. To continue receiving API and SDK improvements, we recommend migrating to our latest APIs and SDKs. You can find instructions for making the switch within the README of each legacy SDK repo below.** > ### /v1 & /v2 Legacy APIs (Deprecated) | 2022 - Node - PHP - Python - Ruby ### /v1 & /v2 Legacy APIs (Deprecated) | 2012 - 2021 - Node.js (legacy) - PHP (legacy) - Python (legacy) - Ruby (legacy) > [!WARNING] > **NOTE: /v1 & /v2 Legacy APIs (Deprecated) | 2012 - 2021 SDKs do not support all API operations** > If you are currently using a legacy SDK, you may be missing some key functionality. For that reason, we recommend customers use our latest SDKs. > > Alternatively, if you'd like to continue using a legacy SDK (e.g: for multi-threading/multi-store support as we work on updating this feature), you can make newer API calls that are not in the SDK by making HTTPS requests outright. For help with this, you can reference our language-specific code examples within the [API reference](https://developers.klaviyo.com/en/v1-2/reference/track-identify-overview), which lists all available operations. --- # Agent skills > Agent skills are step-by-step instructions that an AI coding agent such as Claude Code, Cursor or Codex follows to build on the Klaviyo API. Each one is a short SKILL.md that links to the reference and code files it needs, all in Markdown. Point your agent at the one that fits what you're building. --- # Klaviyo API Key → OAuth Migration Skill > This is the Markdown version of https://developers.klaviyo.com/en/agents/skills/klaviyo-migrate-oauth You are a Klaviyo integration expert. Your job is to guide developers through migrating an existing Klaviyo private API key integration to OAuth 2.0 with PKCE. This is a multi-step process — work through it methodically, starting with a full audit before changing any code. Always match the user's existing language and framework. Read their code before prescribing solutions. --- ## Step 0 — Read the codebase first **Before writing a single line of code**, ask the user to share their codebase (or read it if already available). You need to understand: 1. What language/framework/runtime are they using? 2. Where is the Klaviyo API key currently set? (env var, hardcoded, config file) 3. How is the auth header set? (shared HTTP client, per-request, SDK) 4. Which Klaviyo endpoints are being called? 5. What `revision` header value are they using (if any)? 6. Do they have any existing token storage, session management, or database? If they can't share the full codebase, ask them to paste: - Their HTTP client setup / Klaviyo wrapper - Their `.env` file structure (values redacted is fine) - A list of Klaviyo endpoints they call --- ## Step 1 — Full codebase audit Read [`references/audit-guide.md`](https://developers.klaviyo.com/.well-known/skills/klaviyo-migrate-oauth/references/audit-guide.md) now for search patterns and how to structure the audit report. Run a thorough audit of the codebase to find: - Every place `Klaviyo-API-Key` is set as an auth header - Every Klaviyo API endpoint being called (needed to determine scopes) - The current `revision` header value(s) in use - Where the API key comes from (env var ideally, or hardcoded) - Any existing token storage infrastructure **Produce an audit report** for the user (see [`references/audit-guide.md`](https://developers.klaviyo.com/.well-known/skills/klaviyo-migrate-oauth/references/audit-guide.md) for the format) that lists: - All files that need to change, with line numbers - The minimal OAuth scope set required based on endpoints used - Whether the revision header needs updating - Whether any storage infrastructure needs to be added Show this to the user and get confirmation before proceeding to code changes. --- ## Step 2 — Create the OAuth app in Klaviyo Tell the user to complete these steps in the Klaviyo UI **before you change any code**: 1. Go to **https://www.klaviyo.com/manage-apps** (requires Owner, Admin, or Manager role) 2. Click **Create app** 3. Fill in app name and description 4. Under **OAuth settings**, set **Redirect URI(s)**: - Local dev: `http://localhost:3001/api/auth/callback` (match their existing server port/path) - Production: `https://yourdomain.com/api/auth/callback` - Add both now — they can be updated later if needed 5. Set **Client type** to **Confidential** 6. Add the **scopes** you identified in Step 1 (from your audit) 7. Copy the **Client ID** and **Client Secret** **PAUSE HERE.** Before writing any code, the project needs the app's credentials in `.env`. **Never ask the user to paste the Client Secret into the chat**: anything in the conversation can end up in logs and transcripts. 1. Create or update the `.env` file in the project root, preserving any existing contents, with these entries and placeholder values: ``` KLAVIYO_CLIENT_ID= KLAVIYO_CLIENT_SECRET= KLAVIYO_REDIRECT_URI=http://localhost:3001/api/auth/callback ``` 2. Ask the user to paste their **Client ID** and **Client Secret** into `.env` themselves, then tell you when they're done. 3. Check that both values are set without printing them: `grep -cE '^KLAVIYO_CLIENT_ID=.+' .env` and `grep -cE '^KLAVIYO_CLIENT_SECRET=.+' .env` should each print `1`. Count the keys separately: one `KLAVIYO_CLIENT_(ID|SECRET)` pattern counts matching lines, so duplicates of one key pass for the other. Also run `grep -c '^KLAVIYO_CLIENT_ID=' .env` and `grep -c '^KLAVIYO_CLIENT_SECRET=' .env`, which count empty assignments too; each must print `1`, because dotenv loads the last assignment and a trailing empty one would blank the value. If either prints more, ask the user to remove the duplicates. Do not proceed until both values are set. Use the port and callback path that matches their existing server config (from your Step 0 audit), not necessarily `3001`. Also ensure `.env` is in `.gitignore` — add it if it isn't already. **Wire up dotenv** — env vars in `.env` are not automatically loaded in Node.js. Install and initialize dotenv: ```bash npm install dotenv ``` Then add this as the **very first line** of `server.js` (before any imports that read `process.env`): ```javascript // ESM (package.json has "type": "module") import 'dotenv/config'; // CommonJS (no "type": "module") require('dotenv').config(); ``` Check `package.json` — if it has `"type": "module"`, use the ESM form; otherwise use `require`. This applies whether they run `node server.js` or `npm run dev`. And remind them to **remove** (or plan to remove) `KLAVIYO_API_KEY` from their env — but keep it working in parallel until OAuth is fully tested. Do not proceed to Step 3 until you have written the `.env` file and wired up dotenv. --- ## Step 3 — Determine required scopes Read [`references/scopes.md`](https://developers.klaviyo.com/.well-known/skills/klaviyo-migrate-oauth/references/scopes.md) now for the full scope reference table. From your audit, map every endpoint the integration calls to its required scope. Then: 1. Present the scope list to the user with a brief explanation of what each grants 2. Remind them: **`accounts:read` is always required**, even if they don't explicitly call `/accounts/` 3. Confirm they've added these scopes to the Klaviyo app they just created --- ## Step 4 — Set up token storage Read [`references/storage.md`](https://developers.klaviyo.com/.well-known/skills/klaviyo-migrate-oauth/references/storage.md) now. Check what storage the existing codebase has: - **Has a database?** Add an `oauth_connections` table or equivalent. See [`references/storage.md`](https://developers.klaviyo.com/.well-known/skills/klaviyo-migrate-oauth/references/storage.md) for schema. - **Has Redis?** Use it for token storage. See [`references/storage.md`](https://developers.klaviyo.com/.well-known/skills/klaviyo-migrate-oauth/references/storage.md) for the pattern. - **Has nothing?** Implement `storage.json` for now to get them running quickly. Add a prominent `TODO: production storage` comment. Always gitignore it. Set up the storage layer before implementing the OAuth flow — the flow depends on it. --- ## Step 5 — Implement the OAuth flow Read [`references/pkce-examples.md`](https://developers.klaviyo.com/.well-known/skills/klaviyo-migrate-oauth/references/pkce-examples.md) now for complete implementations in the user's language. Add two new endpoints alongside the existing code (don't remove the API key path yet): ### Auth start (GET /auth/start or equivalent) 1. Generate PKCE: `codeVerifier`, `codeChallenge` (SHA-256, base64url), `state` 2. Store `{ codeVerifier, state }` in PKCE storage 3. Build Klaviyo authorization URL (`https://www.klaviyo.com/oauth/authorize`) 4. Redirect user or return URL to frontend ### Auth callback (GET /auth/callback or equivalent) 1. Verify `state` matches stored value — return 400 if not (CSRF check) 2. Exchange auth code for tokens via `POST https://a.klaviyo.com/oauth/token` — **not www.klaviyo.com** 3. Store tokens: `accessToken`, `refreshToken`, `expiresAt = now + (expires_in * 1000)` 4. Clear PKCE state from storage 5. Immediately call `GET /accounts/` with the new token to verify it works 6. Redirect to connected state Also implement: - **Token refresh**: `getFreshToken()` — refresh if token expires within 5 minutes, handle `invalid_grant` - **Disconnect**: Revoke token at `POST https://a.klaviyo.com/oauth/revoke`, clear stored tokens > **Critical**: Token exchange, refresh, and revoke all go to `a.klaviyo.com` — NOT `www.klaviyo.com`. Klaviyo blocked www for these endpoints as of March 31, 2025. --- ## Step 6 — Swap the auth header Read [`references/api-calls.md`](https://developers.klaviyo.com/.well-known/skills/klaviyo-migrate-oauth/references/api-calls.md) now for the reusable API client pattern. This is the core of the migration. Find the central place where `Klaviyo-API-Key` is set and replace it: ``` // Remove Authorization: Klaviyo-API-Key // Add Authorization: Bearer ``` **Strategy**: Find the single shared HTTP client or wrapper (identified in your audit) and make the change there. All downstream API calls should inherit it automatically. If auth headers are set on every individual request (no shared client), create a wrapper function now: ```javascript // Node.js example async function klaviyoRequest(method, path, options = {}) { const token = await getFreshToken(); return fetch(`https://a.klaviyo.com/api${path}`, { method, headers: { Authorization: `Bearer ${token}`, revision: '2026-10-15', accept: 'application/vnd.api+json', ...options.headers, }, ...options, }); } ``` Then update every API call to use this wrapper instead of raw fetch/requests. --- ## Step 7 — Update the revision header Read [`references/revision-changes.md`](https://developers.klaviyo.com/.well-known/skills/klaviyo-migrate-oauth/references/revision-changes.md) now. Current stable revision: **`2026-10-15`** Check what revision the existing code uses (from your audit) and flag accordingly: - **`2022-*`, `2023-*` or `2024-*`**: **Retired** — must upgrade, may have breaking changes, test carefully - **`2025-*`**: Deprecated — still supported, but upgrade now - **Missing entirely**: Must add — `revision: 2026-10-15` on every request - **`2026-*`**: Up to date **How to upgrade safely:** 1. Update the revision in the shared HTTP client (one change) 2. Test every endpoint the integration uses in a Klaviyo test/sandbox account 3. Check the Klaviyo changelog for changes between their old revision and `2026-10-15`: https://developers.klaviyo.com/en/changelog 4. If upgrading from a retired revision, use `X-Klaviyo-Revision-Fall-Forward-Opt-Out: 1` temporarily to surface 410 errors on broken endpoints If there are potentially breaking changes between their revision and the current one, call them out explicitly with what to watch for. --- ## Step 8 — Handle existing users If this is a multi-tenant app with existing users on API key auth, they all need to re-authorize through the new OAuth flow. ### The transition plan: 1. **Run OAuth and API key in parallel** — don't remove API key support yet 2. **Add a "Reconnect with OAuth" prompt** in your UI for existing users 3. **Detect which auth method a user is on** and route accordingly in your API calls 4. **Set a migration deadline** — once all users have completed OAuth auth, remove the API key path 5. **Klaviyo recommendation**: Within 3 months of migrating your app to OAuth, migrate all customers still on private-key authentication to it For single-tenant / internal tools, the migration is simpler: complete the OAuth flow once, store the tokens, and remove the API key from your env. --- ## Step 9 — Test the full flow Walk the user through testing every part: 1. **Auth flow**: Start → Klaviyo consent page → Callback → tokens stored → redirect to dashboard 2. **API calls**: Each endpoint that was previously working with API key should work with Bearer token 3. **Token refresh**: Simulate by setting `expiresAt` to `Date.now()` and making an API call — confirm refresh happens 4. **Disconnect**: Confirm tokens are cleared, user is returned to unauthenticated state 5. **Reconnect**: Confirm they can go through the OAuth flow again after disconnecting --- ## Step 10 — Final cleanup checklist Once everything is tested and working: - [ ] OAuth app created in Klaviyo with correct redirect URIs and scopes - [ ] `KLAVIYO_CLIENT_ID` in environment variables - [ ] `KLAVIYO_CLIENT_SECRET` in environment variables - [ ] `dotenv` installed and `import 'dotenv/config'` (or `require('dotenv').config()`) is the first line of `server.js` — otherwise env vars will be `undefined` at runtime - [ ] `KLAVIYO_API_KEY` removed from env (or kept temporarily during rollout) - [ ] `storage.json` added to `.gitignore` - [ ] Auth start endpoint working - [ ] Callback endpoint working with state verification - [ ] Token refresh working, `invalid_grant` handled - [ ] Disconnect endpoint working (revokes + clears tokens) - [ ] All API calls use `Bearer` token - [ ] All API calls use `revision: 2026-10-15` - [ ] Existing users have a path to re-authorize (multi-tenant apps) - [ ] `TODO: production storage` comment present if using `storage.json` for now - [ ] Klaviyo API key removed from source code and git history (use `git log -S "pk_"` to check) --- ## Common mistakes to proactively catch 1. **`www.klaviyo.com` for token/revoke calls** — must be `a.klaviyo.com`. This is a common copy-paste mistake that's been breaking integrations since March 2025. 2. **Keeping API key as fallback in production** — it's fine during migration testing, but flag it: "remember to remove the API key fallback before going to production" 3. **No `invalid_grant` handling** — if the refresh token expires (90-day inactivity) or the user uninstalls, and you don't catch this, users silently break with cryptic errors 4. **Tokens returned to the browser** — OAuth tokens should never appear in responses to the frontend 5. **Hardcoded client secret** — if it's in source code, rotate it immediately and use env vars 6. **Forgetting to gitignore `storage.json`** — this file contains live OAuth tokens 7. **Revision not updated** — common to migrate auth but forget the revision header; old revisions are deprecated/retired 8. **Scope too broad** — requesting more than needed will block marketplace submission; audit endpoints → scopes precisely 9. **Missing dotenv initialization** — setting vars in `.env` does nothing unless `dotenv.config()` runs before the first `process.env` read. If `client_id` or `client_secret` are `undefined` at runtime, this is the first thing to check. The import/require must be at the TOP of the entry file, before any routes or config that reads env vars. --- ## Reference files - [`references/audit-guide.md`](https://developers.klaviyo.com/.well-known/skills/klaviyo-migrate-oauth/references/audit-guide.md) — How to find all API key usage and produce an audit report - [`references/scopes.md`](https://developers.klaviyo.com/.well-known/skills/klaviyo-migrate-oauth/references/scopes.md) — Full scope table and common integration patterns - [`references/pkce-examples.md`](https://developers.klaviyo.com/.well-known/skills/klaviyo-migrate-oauth/references/pkce-examples.md) — Copy-paste PKCE implementations in Node.js and Python - [`references/storage.md`](https://developers.klaviyo.com/.well-known/skills/klaviyo-migrate-oauth/references/storage.md) — Token storage patterns (storage.json, database, Redis) - [`references/api-calls.md`](https://developers.klaviyo.com/.well-known/skills/klaviyo-migrate-oauth/references/api-calls.md) — Reusable API client code and auth header examples - [`references/revision-changes.md`](https://developers.klaviyo.com/.well-known/skills/klaviyo-migrate-oauth/references/revision-changes.md) — Revision lifecycle, what changed between versions, how to upgrade safely --- > Reading this skill from the web rather than installing it? Each file it mentions is published next to this SKILL.md: a Markdown file at the same path, and any other file at its path plus `.md`, wrapped in a fenced code block. Fetch a file only when a step needs it, and write a code file out by saving just the contents of its code block. Steps that run `$SKILL/...` mean the skill's directory; if the skill isn't installed, fetch those files first. # Klaviyo New OAuth Integration Skill You are a Klaviyo integration expert. Your job is to guide developers through building a complete, production-ready Klaviyo OAuth integration from scratch. You adapt to whatever language and framework the user is working in — match their stack exactly. When in doubt, ask. Work through the steps below in order, but adapt based on what the user already has. If they share existing code, read it first to understand their stack before prescribing anything. --- ## Step 0 — Understand their situation Before writing any code, ask or infer: - What language and framework are they using? (Node.js/Express, Python/Flask, Ruby/Rails, etc.) - What do they want to DO with Klaviyo? (sync profiles, send campaigns, track events, read lists, etc.) - Do they already have a Klaviyo account with admin access? - Are they building for a single account (internal tool) or multi-tenant (SaaS / marketplace app)? If they share a codebase, **read the relevant files first** to understand: - What language/framework/package manager they use - How their server is structured (routes, middleware) - Whether they have any existing HTTP client setup or auth patterns - Where they currently store config/secrets --- ## Step 1 — Determine required scopes Read [`references/scopes.md`](https://developers.klaviyo.com/.well-known/skills/klaviyo-new-oauth/references/scopes.md) now for the full scope reference table. Ask the user what Klaviyo APIs they plan to call, or look at their existing code to figure it out. Then: 1. Map their use cases to the minimum required scopes using the table in [`references/scopes.md`](https://developers.klaviyo.com/.well-known/skills/klaviyo-new-oauth/references/scopes.md) 2. **Always include `accounts:read`** — it is required for every OAuth app 3. Present the scope list to the user and explain what each one grants 4. Warn them: requesting unnecessary scopes will get their app rejected from the Klaviyo marketplace Give them the scope string they'll need — space-separated: ``` accounts:read lists:read profiles:write events:write ``` The app is created with these scopes in Step 2. If they change later, update the app's scopes too (in the Klaviyo UI, or with the beta Update Application API), or the OAuth flow will be refused. --- ## Step 2 — Create the OAuth app in Klaviyo First work out, from the user's code or by asking: - the **redirect URI** their server will handle the callback on: `http://localhost:3001/api/auth/callback` for a new project, or the port and path their server already uses. Add the production one too if they know it. - the **scopes** from Step 1. - a **title** for the app, as account users will see it when they connect it. Then create the app one of two ways. Either way, **never ask the user to paste the Client Secret into the chat**: anything in the conversation can end up in logs and transcripts. ### Option A: create it through the API (preferred) Klaviyo's Create Application endpoint is in **beta** (revision `2026-10-15.pre`), so tell the user that before you use it. It needs a **private API key with the `applications:write` scope** from the account that will own the app. 1. Ask the user to set the key in their shell, not in the chat: `export KLAVIYO_API_KEY=pk_...`. If they don't have one with `applications:write`, use Option B. 2. Show the user the exact title, redirect URIs and scopes you're about to create the app with, and wait for their approval: creating it makes a real app on their account, and a wrong inferred value is easier to fix before than after. 3. Run the skill's [`scripts/create-oauth-app.mjs`](https://developers.klaviyo.com/.well-known/skills/klaviyo-new-oauth/scripts/create-oauth-app.mjs.md) (Node 18+, no dependencies) by its path in the skill's install directory, and point `--env` at the `.env` in the user's project root, because the script writes to `./.env` of wherever it runs: ```bash node /scripts/create-oauth-app.mjs \ --env /.env \ --title "" \ --redirect-uri http://localhost:3001/api/auth/callback \ --scopes "accounts:read lists:read profiles:write events:write" ``` For several redirect URIs, separate them with commas. 4. The script: - generates a throwaway RSA key pair and sends only its public half - calls `POST https://a.klaviyo.com/api/applications` with the title, redirect URIs and scopes - decrypts the client secret Klaviyo returns (encrypted to that key, and returned only once) - writes `KLAVIYO_CLIENT_ID`, `KLAVIYO_CLIENT_SECRET` and `KLAVIYO_REDIRECT_URI` to `.env`, readable only by its owner It prints the app's ID and client ID, never the secret. 5. If it fails, show the user the error it prints. A `403` usually means the key lacks `applications:write`. If the app was created but the secret couldn't be decrypted, have the user generate a new client secret for that app in the UI (the app and its settings are kept); delete and create the app again only if they can't, because the secret can't be fetched a second time. The app starts as a **draft**: it works for the account that owns it, which is all local development needs. Listing it on the Klaviyo marketplace is a separate review. ### Option B: create it in the Klaviyo UI If there's no key with `applications:write`, or the API call fails, have the user create the app themselves: 1. Go to **https://www.klaviyo.com/manage-apps** (they must be an account Owner, Admin, or Manager). 2. Click **Create app**, and fill in the app name and description. 3. Under **OAuth settings**, set the **Redirect URI(s)** to exactly the URLs above. Add both the local and production ones now. 4. Set **Client type** to **Confidential**, and add the scopes from Step 1. 5. After creating, note the **Client ID**, and save the **Client Secret** somewhere secure: Klaviyo shows it only once. Then: 1. Create or update the `.env` file in the project root, preserving any existing contents, with these entries and placeholder values: ``` KLAVIYO_CLIENT_ID= KLAVIYO_CLIENT_SECRET= KLAVIYO_REDIRECT_URI=http://localhost:3001/api/auth/callback ``` 2. Ask the user to paste their **Client ID** and **Client Secret** into `.env` themselves, then tell you when they're done. ### Either way > **Note on redirect URIs**: Klaviyo also allows installation from its own marketplace — meaning the redirect must work from `klaviyo.com` subdomains too, not just your own domain. For local dev this doesn't apply, but flag it for production. Check that both values are set without printing them: `grep -cE '^KLAVIYO_CLIENT_ID=.+' .env` and `grep -cE '^KLAVIYO_CLIENT_SECRET=.+' .env` should each print `1`. Count the keys separately, not with one `KLAVIYO_CLIENT_(ID|SECRET)` pattern: that counts matching lines, so two `CLIENT_ID` lines and no `CLIENT_SECRET` also print `2`. Do not proceed until both are set, each exactly once. Remind the user: never hardcode these values in source files. Also ensure `.env` is in `.gitignore` — add it if it isn't already. **Wire up dotenv** — env vars in `.env` are not automatically loaded in Node.js. Install and initialize dotenv: ```bash npm install dotenv ``` Then add this as the **very first line** of `server.js` (before any imports that read `process.env`): ```javascript // ESM (package.json has "type": "module") import 'dotenv/config'; // CommonJS (no "type": "module") require('dotenv').config(); ``` Check `package.json` — if it has `"type": "module"`, use the ESM form; otherwise use `require`. This applies whether they run `node server.js` or `npm run dev`. Do not proceed to Step 3 until you have written the `.env` file and wired up dotenv. --- ## Step 3 — Implement token storage Read [`references/storage.md`](https://developers.klaviyo.com/.well-known/skills/klaviyo-new-oauth/references/storage.md) now. Before implementing the OAuth flow, set up storage — you need somewhere to persist tokens. - **Local dev / getting started quickly**: Use `storage.json` — implement it now using the pattern in [`references/storage.md`](https://developers.klaviyo.com/.well-known/skills/klaviyo-new-oauth/references/storage.md) - **Production**: Use an encrypted database column or secret manager — call this out with a `TODO` comment if you're setting up local dev storage for now Key things to store: `accessToken`, `refreshToken`, `expiresAt`, `accountId`, `accountName`. Also set up PKCE state storage (lives for only ~5 minutes during the OAuth flow): - Local dev: same `storage.json` file with a `pkce` key - Production: Redis with short TTL or server-side session If the codebase already has a database or session layer, use it — don't add storage.json if something better exists. --- ## Step 4 — Implement the PKCE OAuth flow Read [`references/pkce-examples.md`](https://developers.klaviyo.com/.well-known/skills/klaviyo-new-oauth/references/pkce-examples.md) now for complete, copy-paste implementations in the user's language. The flow has three parts: ### Part A: Auth start endpoint (GET /auth/start or equivalent) 1. Generate `codeVerifier`, `codeChallenge` (SHA-256 of verifier, base64url), and `state` (CSRF token) 2. Store `{ codeVerifier, state }` in your PKCE storage (cleared after callback) 3. Build the authorization URL — always uses `https://www.klaviyo.com/oauth/authorize` 4. Redirect the user (or return the URL to the frontend to redirect) Required URL parameters: ``` response_type=code client_id= redirect_uri= scope= state= code_challenge= code_challenge_method=S256 ``` ### Part B: Callback endpoint (GET /auth/callback or equivalent) This is where Klaviyo sends the user after they authorize. 1. Check for `?error` param — if present, show the user a clear error (e.g., "access_denied") 2. Verify `state` matches what you stored — return 400 if not (CSRF protection) 3. Retrieve `codeVerifier` from storage using the state as key 4. Exchange the code for tokens via `POST https://a.klaviyo.com/oauth/token`: - Add `Authorization: Basic base64(client_id:client_secret)` header 5. Store the returned `access_token`, `refresh_token`, `expires_at = now + expires_in * 1000` 6. Clear PKCE state from storage 7. Immediately fetch account info (GET /accounts/) to verify the token works and get account details 8. Redirect to your app's connected/dashboard state > **Critical URL note**: Token exchange goes to `https://a.klaviyo.com/oauth/token` — NOT `www.klaviyo.com`. Using `www` for token calls is blocked by Klaviyo as of March 31, 2025. ### Part C: Token refresh Wire this into a `getFreshToken()` function that is called before **every** API request: 1. Check if `expiresAt - now < 5 minutes` 2. If so, POST to `https://a.klaviyo.com/oauth/token` with `grant_type=refresh_token` 3. Update stored tokens with the new values (refresh token may or may not rotate — always use whatever comes back) 4. On `invalid_grant` error: the user has uninstalled or the refresh token expired (90-day inactivity limit) → clear stored tokens and surface a "reconnect required" error to the user 5. Return the valid access token --- ## Step 5 — Add a disconnect endpoint Users must be able to disconnect. When they do: 1. Call `POST https://a.klaviyo.com/oauth/revoke` with the access token (best-effort — don't throw on failure) 2. Clear all stored tokens from your storage 3. Return the user to the disconnected/login state --- ## Step 6 — Make API calls with Bearer token Read [`references/api-calls.md`](https://developers.klaviyo.com/.well-known/skills/klaviyo-new-oauth/references/api-calls.md) now for the reusable API client pattern and examples. The key change from API key auth: ``` // Before Authorization: Klaviyo-API-Key pk_xxxxxxx // After Authorization: Bearer ``` Build one central API client that: - Calls `getFreshToken()` before every request (auto-refresh) - Sets `Authorization: Bearer ` - Sets `revision: 2026-10-15` on every request - Handles errors and surfaces useful messages Show them example calls for the endpoints they said they'd be using. --- ## Step 7 — Revision header audit Always flag the revision header. Current stable revision: **`2026-10-15`** - Revisions follow a 2-year lifecycle: 1 year stable → 1 year deprecated → retired (410 errors) - Any revision from 2024 or earlier is retired, and `2025-*` revisions are deprecated - Use `X-Klaviyo-Revision-Fall-Forward-Opt-Out: 1` if you want explicit errors instead of silent fall-forward on a retired revision - Tell the user to plan for a revision update every 12–18 months --- ## Step 8 — Final checklist Before wrapping up, run through this with the user: - [ ] OAuth app created in Klaviyo with correct redirect URIs and scopes (through the API or the UI) - [ ] `KLAVIYO_CLIENT_ID` and `KLAVIYO_CLIENT_SECRET` in environment variables - [ ] `dotenv` installed and `import 'dotenv/config'` (or `require('dotenv').config()`) is the first line of `server.js` — otherwise env vars will be `undefined` at runtime - [ ] `storage.json` gitignored (or production storage in place) - [ ] Auth start endpoint working — generates PKCE, redirects to Klaviyo - [ ] Callback endpoint working — exchanges code, stores tokens, verifies with `/accounts/` - [ ] Token refresh working — proactive refresh before expiry, handles `invalid_grant` - [ ] Disconnect endpoint working — revokes token, clears storage - [ ] All API calls use `Bearer` token (not API key) - [ ] All API calls include `revision: 2026-10-15` - [ ] `TODO: production storage` comment left if using `storage.json` for now --- ## Common mistakes to proactively catch 1. **`www.klaviyo.com` for token calls** — must be `a.klaviyo.com` for `/oauth/token` and `/oauth/revoke` 2. **Tokens returned to the browser** — access/refresh tokens should never appear in frontend API responses 3. **No `invalid_grant` handling** — if refresh fails and you don't catch it, users silently break 4. **Requesting new tokens before every call** — always reuse the stored token until it's near expiry 5. **Hardcoded client secret** — must live in env vars or secret manager, never in source code 6. **Missing `revision` header** — every Klaviyo API call requires it 7. **Scope mismatch** — 403 errors usually mean the scope wasn't added in the Klaviyo app settings 8. **State not verified on callback** — skipping CSRF check is a security vulnerability 9. **Missing dotenv initialization** — setting vars in `.env` does nothing unless `dotenv.config()` runs before the first `process.env` read. If `client_id` or `client_secret` are `undefined` at runtime, this is the first thing to check. The import/require must be at the TOP of the entry file, before any routes or config that reads env vars. --- ## Reference files - [`references/scopes.md`](https://developers.klaviyo.com/.well-known/skills/klaviyo-new-oauth/references/scopes.md) — Full scope table and common integration patterns - [`references/pkce-examples.md`](https://developers.klaviyo.com/.well-known/skills/klaviyo-new-oauth/references/pkce-examples.md) — Copy-paste PKCE implementations in Node.js and Python - [`references/storage.md`](https://developers.klaviyo.com/.well-known/skills/klaviyo-new-oauth/references/storage.md) — Token storage patterns (storage.json, database, Redis) - [`references/api-calls.md`](https://developers.klaviyo.com/.well-known/skills/klaviyo-new-oauth/references/api-calls.md) — Reusable API client code and common endpoint examples - [`scripts/create-oauth-app.mjs`](https://developers.klaviyo.com/.well-known/skills/klaviyo-new-oauth/scripts/create-oauth-app.mjs.md) — Creates the OAuth app through the beta Create Application API and writes its credentials to `.env` (Step 2, Option A) --- > Reading this skill from the web rather than installing it? Each file it mentions is published next to this SKILL.md: a Markdown file at the same path, and any other file at its path plus `.md`, wrapped in a fenced code block. Fetch a file only when a step needs it, and write a code file out by saving just the contents of its code block. Steps that run `$SKILL/...` mean the skill's directory; if the skill isn't installed, fetch those files first. # Klaviyo onsite forms for a Vercel Shop storefront This skill builds and manages Klaviyo onsite forms (popups, flyouts, full-screen forms, banners and embeds) for one storefront, from the terminal. The forms need no storefront code: `klaviyo.js` renders a form once it's live and its targeting matches the page, and Vercel Shop's Klaviyo integration tells `klaviyo.js` about client-side navigation so targeting re-evaluates without a reload. A Klaviyo account is often shared with another storefront for the same Shopify store, such as the Shopify theme it's replacing. So this skill owns only forms named `Vercel Shop - `, gives every version of every form a URL allow list naming only this storefront's hosts, and treats every other form as read-only. Ask before creating, publishing, unpublishing or deleting anything: a published form shows to real shoppers. ## Step 0 — Check what's there 1. **`klaviyo.js` is on the storefront.** In Vercel Shop, `lib/klaviyo/client.ts` exists and `analytics.klaviyo.isEnabled` is on. If not, apply `klaviyo-vercel-shop` first: without it a form can be published but never renders. 2. **The Klaviyo MCP server is connected** (`https://mcp.klaviyo.com/mcp`). Its `get_forms`, `get_form`, `create_form` and `delete_form` tools read forms, create drafts and delete them. 3. **A private key for editing and publishing, if needed.** Changing an existing form and publishing go through the REST API, which needs a private key with `forms:read` and `forms:write`. Ask the user to `export KLAVIYO_API_KEY=...` in their own shell. Never take it in the chat, and never put it in `.env` files the storefront reads, the Vercel project or a commit. Without one, the user can edit and publish the draft in Klaviyo's form editor instead. ## Step 1 — Ask Ask these together: 1. **What form?** Type (popup, flyout, full screen, banner, embed), offer, copy, when it shows (delay, scroll, exit intent) and on which pages. 2. **Which hosts does the storefront run on?** Usually `localhost`, `127.0.0.1`, the `.vercel.app` production domain and any custom domain. These go in every form's targeting. If the public key has a domain allowlist, each host must be on it too, or the form displays but doesn't submit. 3. **Which list do signups join?** Suggest the storefront's signup list (`NEXT_PUBLIC_KLAVIYO_LIST_ID`), so form signups get the same welcome flow as the footer form. ## Step 2 — Create the form as a draft Don't write a form definition from scratch: it has many required fields. Start from a working one. 1. Call `get_forms`, pick a form of the type the user wants, preferably a simple one (a text block, an email field, a submit button and a success step), and call `get_form` on it. Save its output as `source.json`. 2. Make a clean draft from it: ```bash node /scripts/forms.mjs prepare source.json \ --name "Vercel Shop - " \ --hosts localhost,127.0.0.1,.vercel.app \ --out new-form.json ``` This strips every `id`, drops each version's name, status, A/B setting and teasers, and replaces each version's URL targeting with only these hosts. The source form is untouched. 3. Edit `new-form.json` as the user asked, following [`references/form-definition.md`](https://developers.klaviyo.com/.well-known/skills/klaviyo-onsite-forms/references/form-definition.md): the copy, styles and images, the submit button's list, and the trigger. 4. Check the targeting again, then call `create_form` with the file's `name`, `status` (`draft`), `ab_test` (`false`) and `definition`: ```bash node /scripts/forms.mjs check new-form.json --hosts localhost,127.0.0.1,.vercel.app ``` Forms are always created as drafts. Tell the user its ID and that they can preview it in Klaviyo's form editor. ## Step 3 — Edit a form Updating replaces the whole definition and changes only draft versions. A published form keeps a draft next to its live version, so edit the draft and publish again; the live version stays up until then. ```bash node /scripts/forms.mjs get --out form.json # edit only the draft versions in form.json node /scripts/forms.mjs update --file form.json --hosts localhost,127.0.0.1,.vercel.app ``` `update` refuses (exit 3) a form without the `Vercel Shop - ` prefix, a changed live version, an added or removed version, a missing version ID, or targeting outside the hosts. If it reports that the form changed since it was read, run `get` again, reapply the change and retry. ## Step 4 — Publish or take it down Ask the user first. Publishing replaces the live version with the draft and shows it to shoppers. ```bash node /scripts/forms.mjs publish --hosts localhost,127.0.0.1,.vercel.app node /scripts/forms.mjs unpublish ``` `publish` checks the prefix and that every version targets only these hosts, then waits until the form is live. A `400` explains what blocks publishing. A `409` means the form has an A/B test, which only Klaviyo's form editor can manage. To delete a form, unpublish it, then call `delete_form`. ## Step 5 — Check it renders 1. Open the storefront in a private window: Klaviyo hides forms from identified profiles, and from visitors who already submitted or closed them. 2. Wait for the trigger (the delay, scroll or exit intent). Changes can take a minute or two to reach Klaviyo's form cache. 3. Navigate client-side to a page the targeting excludes, and check that the form doesn't appear there. 4. Submit a new test address on a domain the user controls. The profile joins the list, and the form's submits show up in `query_form_values`. If it doesn't render, read [`references/troubleshooting.md`](https://developers.klaviyo.com/.well-known/skills/klaviyo-onsite-forms/references/troubleshooting.md). ## Pitfalls - **A form with no URL allow list.** It shows on every site that uses the account, including a live Shopify theme. `prepare`, `update` and `publish` enforce one on every version; don't publish another way to get around it. - **Editing someone else's form.** Forms without the `Vercel Shop - ` prefix belong to another storefront or team. Read them, copy them, never change them. - **Changing an image without clearing `asset_id`.** Klaviyo keeps showing the library image. Set `src` and clear `asset_id` together. - **An empty row.** Removing every block from a row leaves an invalid definition. Remove the row. - **A second `klaviyo.js`.** Forms on a page with two copies lose their state. Load it only through the storefront's integration. - **A private key in the storefront.** It's for the developer's shell only. Anything the storefront needs works with the public key. ## Reference files - [`references/form-definition.md`](https://developers.klaviyo.com/.well-known/skills/klaviyo-onsite-forms/references/form-definition.md): the parts of a form definition you'll edit, and the fields create rejects - [`references/troubleshooting.md`](https://developers.klaviyo.com/.well-known/skills/klaviyo-onsite-forms/references/troubleshooting.md): why a form doesn't show, doesn't submit, or won't publish - [`scripts/forms.mjs`](https://developers.klaviyo.com/.well-known/skills/klaviyo-onsite-forms/scripts/forms.mjs.md): prepare, check, get, update, publish and unpublish, with the prefix and targeting guards --- # Klaviyo analytics and draft campaigns for a storefront > This is the Markdown version of https://developers.klaviyo.com/en/agents/skills/klaviyo-store-analytics This skill answers questions about a store's Klaviyo data, and turns the answers into draft segments and campaigns, through the Klaviyo MCP server. It knows what a Vercel Shop storefront sends to Klaviyo (Viewed Product, Added to Cart, Viewed Collection, Submitted Search, Active on Site, list signups with their source, back-in-stock subscriptions and, with Shop Agent, Used Shop Agent), so it can answer questions about the new storefront as well as the account as a whole. Reporting is read-only. Anything a shopper could receive is created as a draft, and a person reviews and sends it in Klaviyo. **Never call `send_campaign`, `create_template_preview_send_job`, or anything else that sends a message, and never set a flow live from this skill.** ## Step 0 — Connect Use Klaviyo's remote MCP server, `https://mcp.klaviyo.com/mcp`. For reporting only, add `?read-only=true` to the URL, so the server exposes no tool that can change the account. Drafting campaigns needs the full server. Call `get_account_details` and confirm the account name with the user before answering: an agent signed in to the wrong account answers about the wrong store. ## Step 1 — Pin down the question Before running anything, settle: - **The date range**, as calendar dates in the account's timezone (from `get_account_details`). "Last month" is the previous calendar month, not the last 30 days, unless the user says otherwise. - **The metric.** Look up metric IDs with `get_metrics`; names alone are ambiguous when several integrations define the same one (two `Placed Order` metrics, from Shopify and from an API integration, is common). - **The denominator** for any rate: recipients, delivered, opens, sessions. - **The scope:** the whole account, or only this storefront. [`references/storefront-events.md`](https://developers.klaviyo.com/.well-known/skills/klaviyo-store-analytics/references/storefront-events.md) says how to tell the storefront's activity apart. Ask when the question leaves one of these open and the answer depends on it. ## Step 2 — Answer it [`references/questions.md`](https://developers.klaviyo.com/.well-known/skills/klaviyo-store-analytics/references/questions.md) has recipes for common questions: revenue by channel, campaigns ranked by click rate, flow reach and engagement, storefront signups, form performance, Shop Agent usage, and one shopper's history. In general: - **Event counts, sums and trends:** `query_metric_aggregates`, with the metric ID, the measurement (`count`, `sum_value`, `unique`), the date range, an interval, and a grouping where the metric supports it. - **Campaigns and flows:** `get_campaign_report` and `get_flow_report`, with the statistics you need and the conversion metric (usually Placed Order) for revenue. - **Forms and segments:** `query_form_values`, `query_form_series`, `query_segment_values`, `query_segment_series`. - **One shopper:** `get_profiles` with an email filter, then `get_profile` and `get_events` for their activity. Report every number with its date range, metric and denominator, and say what the data can't answer: sparse events, no attribution, or a metric the account doesn't have. Don't pad a weak answer, and don't compute numbers the tools didn't return. Profiles and events contain shoppers' personal data. Show only what the question needs, and don't copy it into files or other tools. ## Step 3 — Draft a campaign, if asked Follow [`references/drafts.md`](https://developers.klaviyo.com/.well-known/skills/klaviyo-store-analytics/references/drafts.md): a segment with `create_segment`, an email with `create_email_template`, and a campaign with `create_campaign` that uses both, every one named `Vercel Shop - `. Show the user the segment definition, the subject line and the audience size estimate first, and create nothing until they approve. End by telling the user where the draft is and that it sends only when a person schedules or sends it in Klaviyo. ## Pitfalls - **Revenue per message that comes back near zero.** Many accounts attribute little revenue to individual campaigns or flows, so check attribution with a channel breakdown before ranking messages by revenue, and say so if it's thin. - **A funnel with no middle.** If Added to Cart is rare or missing for the period (common before a storefront's events are flowing), a view-to-cart-to-order funnel is misleading. Count each step and say which one is sparse. - **The wrong Placed Order.** Pick the metric by its integration, and say which one you used. - **"Last 30 days" versus "last month".** Say which window every number covers. - **A campaign sent by accident.** This skill only drafts. If the user asks to send, tell them to send it from Klaviyo. ## Reference files - [`references/questions.md`](https://developers.klaviyo.com/.well-known/skills/klaviyo-store-analytics/references/questions.md): recipes for common questions, with the tools and parameters - [`references/storefront-events.md`](https://developers.klaviyo.com/.well-known/skills/klaviyo-store-analytics/references/storefront-events.md): what a Vercel Shop storefront sends to Klaviyo, and how to isolate it - [`references/drafts.md`](https://developers.klaviyo.com/.well-known/skills/klaviyo-store-analytics/references/drafts.md): building a segment, template and campaign as drafts --- > Reading this skill from the web rather than installing it? Each file it mentions is published next to this SKILL.md: a Markdown file at the same path, and any other file at its path plus `.md`, wrapped in a fenced code block. Fetch a file only when a step needs it, and write a code file out by saving just the contents of its code block. Steps that run `$SKILL/...` mean the skill's directory; if the skill isn't installed, fetch those files first. # Klaviyo for Vercel Shop This skill connects a Vercel Shop storefront to Klaviyo, so browsing and cart activity, email signups and back-in-stock requests reach Klaviyo, and the flows Klaviyo already runs for Shopify stores (welcome, browse abandonment, abandoned cart, back in stock) work on the headless storefront too. Shopify still owns the catalog, orders and checkout, and Klaviyo's Shopify integration still syncs them. The storefront only adds what a headless site would otherwise lose: onsite activity, which used to come from the Shopify theme. The integration is a destination on the Hydrogen analytics bus that Vercel Shop already uses. It never publishes events itself, it loads `klaviyo.js` only after the shopper's consent allows tracking, and it uses only the public API key (the six-character site ID) and Klaviyo's client APIs. **No Klaviyo private API key ever goes into the storefront, its Vercel environment, or a commit.** Work through the steps in order. Ask before every write to the user's Klaviyo account or Vercel project. ## Step 0 — Check the project 1. Confirm this is Vercel Shop: `package.json` has `"name": "vercel-shop"`, and `lib/analytics/client.ts` exports `addAnalyticsDestination`. Read the `version`. This skill was written against `2026.10.2`; on a later version, read each file before editing it rather than trusting the anchors in [`references/code-changes.md`](https://developers.klaviyo.com/.well-known/skills/klaviyo-vercel-shop/references/code-changes.md). 2. Check whether Klaviyo is already there. If `lib/klaviyo/index.ts` exists, don't copy anything over it: compare it with [assets/lib/klaviyo/index.ts](https://developers.klaviyo.com/.well-known/skills/klaviyo-vercel-shop/assets/lib/klaviyo/index.ts.md), report the differences, and ask before replacing it. Every edit in [`references/code-changes.md`](https://developers.klaviyo.com/.well-known/skills/klaviyo-vercel-shop/references/code-changes.md) says how to tell it's already applied. 3. Check whether the Vercel project is linked (`.vercel/project.json` exists). If not, and the user wants environment variables set from the terminal, ask them to run `vercel link`. ## Step 1 — Ask what the user has and wants Ask these together and wait for every answer: 1. **How is Klaviyo connected?** Through the Klaviyo integration on the Vercel Marketplace (the public key is already in the project's environment), through the Klaviyo MCP server in this agent, or neither (they'll paste the public key). 2. **Which features?** Onsite tracking is always on. The footer signup form needs a list. Back-in-stock alerts need Back in Stock turned on in Klaviyo and the Shopify catalog synced. Signed-in customers are identified automatically when Vercel Shop's customer accounts are on (`auth.isEnabled`); there's nothing to choose. 3. **Is Klaviyo's Shopify integration connected to the same Klaviyo account?** Product-matched flows, back in stock and order events depend on it. The storefront doesn't replace it. 4. **Does the public key have a domain allowlist?** If it does, every storefront host has to be on it, or client calls return `403`. [`references/account-setup.md`](https://developers.klaviyo.com/.well-known/skills/klaviyo-vercel-shop/references/account-setup.md) explains each answer and what to do about it. ## Step 2 — Set up the Klaviyo side Follow [`references/account-setup.md`](https://developers.klaviyo.com/.well-known/skills/klaviyo-vercel-shop/references/account-setup.md): - with the Marketplace integration, pull the existing variables; - with the MCP server, read the account, pick or create the signup list, and offer a welcome flow; - otherwise, have the user paste the public key and list ID. Confirm the account name with the user before writing anything to it. Never pick a list for them, and never set a flow live without asking: a live flow emails every new list member. ## Step 3 — Add the code 1. Copy these files into the project at the same paths, unchanged: - [assets/lib/klaviyo/index.ts](https://developers.klaviyo.com/.well-known/skills/klaviyo-vercel-shop/assets/lib/klaviyo/index.ts.md): event names, payload mapping, the client API call - [assets/lib/klaviyo/client.ts](https://developers.klaviyo.com/.well-known/skills/klaviyo-vercel-shop/assets/lib/klaviyo/client.ts.md): the consent-gated call queue and the one `klaviyo.js` loader - [assets/components/analytics/klaviyo-client.tsx](https://developers.klaviyo.com/.well-known/skills/klaviyo-vercel-shop/assets/components/analytics/klaviyo-client.tsx.md): registers the `klaviyo` destination on the bus - [assets/components/klaviyo/email-capture-form.tsx](https://developers.klaviyo.com/.well-known/skills/klaviyo-vercel-shop/assets/components/klaviyo/email-capture-form.tsx.md): signup and back-in-stock forms - [assets/components/klaviyo/identify.tsx](https://developers.klaviyo.com/.well-known/skills/klaviyo-vercel-shop/assets/components/klaviyo/identify.tsx.md): identifies a signed-in customer 2. Apply every edit in [`references/code-changes.md`](https://developers.klaviyo.com/.well-known/skills/klaviyo-vercel-shop/references/code-changes.md): the config flags, the destination slot in the Shopify scripts tracker, the product image on Viewed Product, the footer form, the back-in-stock form, account identification, `.env.example` and `turbo.json`. Turn off the config flags for features the user didn't choose rather than skipping their edits. Tell the user that turning Klaviyo on also loads Shopify's analytics scripts and, in consent regions, its consent banner (edit 2 explains why). 3. If the storefront sets a Content Security Policy, add Klaviyo's hosts from [`references/csp.md`](https://developers.klaviyo.com/.well-known/skills/klaviyo-vercel-shop/references/csp.md). Stock Vercel Shop sets none. 4. Run `pnpm typecheck` and `pnpm lint`, and fix what they report before going on. ## Step 4 — Set the environment and deploy The public key goes in `NEXT_PUBLIC_KLAVIYO_COMPANY_ID`, and the signup list in `NEXT_PUBLIC_KLAVIYO_LIST_ID`, in all three Vercel environments. `vercel env add` reads the value from stdin: ```bash for env in development preview production; do printf %s "$COMPANY_ID" | vercel env add NEXT_PUBLIC_KLAVIYO_COMPANY_ID "$env" --force printf %s "$LIST_ID" | vercel env add NEXT_PUBLIC_KLAVIYO_LIST_ID "$env" --force done vercel env pull .env.development.local --yes ``` `next dev` gives `.env.development.local` priority over `.env.local`. `NEXT_PUBLIC_` values are compiled into the bundle, so if the project is already deployed, ask before redeploying (`vercel deploy --prod`): the live site only picks them up after a new build. ## Step 5 — Hand over what only the user can do Tell the user, in one list, what's left in Klaviyo that has no API: - connect Klaviyo's Shopify integration (Integrations, then Shopify), if it isn't; - add every storefront host to the public key's allowlist, if it has one; - turn on Back in Stock, if they chose it. ## Step 6 — Verify Run `pnpm dev` with `NEXT_PUBLIC_KLAVIYO_DEBUG="1"` and watch the browser console: 1. Load the home page: `[klaviyo] klaviyo.js loaded after consent`, once (after accepting the consent banner, in a consent region). 2. Open a product: `Viewed Product`, with a numeric `ProductID`. 3. Add it to the cart: one `Added to Cart`, after the cart confirms. 4. Go to another page: `page change`. 5. Submit the footer form with a new test address on a domain the user controls. In Klaviyo, that profile shows the list subscription and the events from steps 2 and 3. 6. If a welcome flow is live, the profile shows Received Email within a few minutes. A profile enters a list-triggered flow only the first time it joins, so use a new address for each test. Debug mode logs every call even without a public key, so the code can be checked before the account is connected. When something doesn't arrive, read [`references/troubleshooting.md`](https://developers.klaviyo.com/.well-known/skills/klaviyo-vercel-shop/references/troubleshooting.md). ## Next - **Shop Agent:** `klaviyo-vercel-shop-agent` lets the storefront's AI shopping assistant sign shoppers up for back-in-stock alerts and records that it did. - **Popups and embedded forms:** `klaviyo-onsite-forms` builds them, scoped to this storefront. - **Reporting:** `klaviyo-store-analytics` answers questions about the storefront's signups, events and flows. ## Pitfalls - **A private key in the storefront.** Everything here runs in the shopper's browser or a shopper-facing agent. A private key there can read and change the whole Klaviyo account. Refuse, even for a "quick test". - **A second `klaviyo.js`.** A manual `