How to integrate a headless Magento 2 setup
You will learn
Learn about how to integrate Klaviyo with a headless Magento 2 setup. If you are using Magento 2 to power your ecommerce store’s backend, but a different framework for the frontend (such as React.js, Angular, etc.), then the following information is relevant for you.
This integration requires 3 steps:
- Connect your Magento 2 store via Klaviyo’s native integration to sync order, catalog, and subscriber data.
- Manually add code snippets to your site to enable onsite tracking functionality.
- (If you are using a custom URL structure for your product catalog) Add rewrite rules for product URLs.
Connect Klaviyo's native integration
First, connect your Magento 2 store via Klaviyo’s native integration to sync order, catalog, and subscriber data by following the steps in Getting started with Magento 2.
A large part of Klaviyo’s Magento 2 integration relies on fetching data via Magento's server side API. Typically, this isn’t affected by using a decoupled frontend, and the native integration will track the following events without further setup:
- Placed Order
- Ordered Product
- Fulfilled Order
- Fulfilled Shipment
- Canceled Order
- Refunded Order
- Started Checkout
Additionally, please note that:
- Started Checkout events sync from active, non-empty Magento quotes with a valid email address. Make sure your headless checkout creates these quotes and saves the email address in the quote’s customer or billing address data. Quotes that are inactive when Klaviyo syncs are skipped.
- If you’ve enabled syncing customers subscribed to the Magento 2 newsletter table, the sync should work as anticipated.
Manually add code snippets
If you are using a headless setup, you must manually add Klaviyo’s “Active on Site” JavaScript (also known as Klaviyo.js) to your site. Klaviyo.js records Active on Site events for visitors Klaviyo can identify and enables Klaviyo forms.
We also provide snippets that allow you to do the following:
- Viewed Product tracking
Track when a user views specific products on your site (which can be leveraged in a browse abandonment flow). - Recently viewed products tracking
Track recently viewed items on a user's profile. - Added to Cart tracking
Track when a user adds an item to their cart. - Logged-in user identification
If you have account creation functionality, identify users in Klaviyo when they log in.
Active on Site
Add the following Klaviyo.js snippet so that it appears on every page on your website. This will enable Active on Site tracking and Klaviyo forms. Make sure to replace PUBLIC_API_KEY with your Klaviyo public API key.
<script type="text/javascript" async="" src="https://static.klaviyo.com/onsite/js/PUBLIC_API_KEY/klaviyo.js"></script>After adding Klaviyo.js, you'll need to load the Klaviyo object on any page where you want to add one of the following snippets (such as Viewed Product, Added to Cart, etc). The klaviyo object only needs to be loaded once per page.
To load the klaviyo object, install the following snippet before any code that calls it:
<script type="text/javascript"> !function(){if(!window.klaviyo){window._klOnsite=window._klOnsite||[];try{window.klaviyo=new Proxy({},{get:function(n,i){return"push"===i?function(){var n;(n=window._klOnsite).push.apply(n,arguments)}:function(){for(var n=arguments.length,o=new Array(n),w=0;w<n;w++)o[w]=arguments[w];var t="function"==typeof o[o.length-1]?o.pop():void 0,e=new Promise((function(n){window._klOnsite.push([i].concat(o,[function(i){t&&t(i),n(i)}]))}));return e}}})}catch(n){window.klaviyo=window.klaviyo||[],window.klaviyo.push=function(){var n;(n=window._klOnsite).push.apply(n,arguments)}}}}(); </script>Viewed Product
If you'd like to set up a browse abandonment flow or build segments based on product browsing activity, you'll need to add JavaScript event tracking for the Viewed Product metric. All Viewed Product events are tied to user profiles. On your product page template, add the following snippet.
Before using this example, replace each item.___ value in the snippet with the corresponding product data from your frontend. Make sure that data is available before the snippet runs. Use customer-facing product and image URLs.
<script type="text/javascript">
var klaviyo = window.klaviyo || [];
var item = {
"ProductName": item.ProductName,
"ProductID": item.ProductID,
"SKU": item.SKU,
"Categories": item.Categories,
"ImageURL": item.ImageURL,
"URL": item.URL,
"Brand": item.Brand,
"Price": item.Price,
"CompareAtPrice": item.CompareAtPrice
};
klaviyo.track("Viewed Product", item);
</script>
Recently viewed products
The following snippet adds products to the Recently viewed products panel on the user’s profile. Add it directly below the Viewed Product snippet so it uses the same product data.
If you use the Viewed Product example above, this snippet can reuse its item object. Otherwise, replace item.___ with the corresponding product values from your frontend.
<script type="text/javascript">
var klaviyo = window.klaviyo || [];
klaviyo.trackViewedItem({
"Title": item.ProductName,
"ItemId": item.ProductID,
"Categories": item.Categories,
"ImageUrl": item.ImageURL,
"Url": item.URL,
"Metadata": {
"Brand": item.Brand,
"Price": item.Price,
"CompareAtPrice": item.CompareAtPrice
}
});
</script>Added to Cart
If you’d like to send abandoned cart emails to visitors who add items to their cart, but don’t make it to the checkout page, you’ll want to track an Added to Cart metric. Klaviyo must be able to identify the visitor to associate the event with their profile. Run the tracking call after an item is successfully added to the cart, using the added item and the updated cart contents. Replace the example values with data from your storefront, including a checkout URL that works on your headless site. Here is an example where the cart already contained 1 item (Winnie the Pooh) and another item was just added (A Tale of Two Cities):
<script type="text/javascript">
klaviyo.track("Added to Cart", {
"$value": 29.98,
"AddedItemProductName": "A Tale of Two Cities",
"AddedItemProductID": "1112",
"AddedItemSKU": "TALEOFTWO",
"AddedItemCategories": ["Fiction", "Classics", "Children"],
"AddedItemImageURL": "http://www.example.com/path/to/product/image2.png",
"AddedItemURL": "http://www.example.com/path/to/product2",
"AddedItemPrice": 19.99,
"AddedItemQuantity": 1,
"ItemNames": ["Winnie the Pooh", "A Tale of Two Cities"],
"CheckoutURL": "http://www.example.com/path/to/checkout",
"Items": [{
"ProductID": "1111",
"SKU": "WINNIEPOOH",
"ProductName": "Winnie the Pooh",
"Quantity": 1,
"ItemPrice": 9.99,
"RowTotal": 9.99,
"ProductURL": "http://www.example.com/path/to/product",
"ImageURL": "http://www.example.com/path/to/product/image.png",
"ProductCategories": ["Fiction", "Children"]
},
{
"ProductID": "1112",
"SKU": "TALEOFTWO",
"ProductName": "A Tale of Two Cities",
"Quantity": 1,
"ItemPrice": 19.99,
"RowTotal": 19.99,
"ProductURL": "http://www.example.com/path/to/product2",
"ImageURL": "http://www.example.com/path/to/product/image2.png",
"ProductCategories": ["Fiction", "Classics"]
}
]
});
</script>Logged in users
If customers can create accounts on your website, use the following code after they log in to identify them in Klaviyo and update their profile details. It does not record a separate login event. Replace the customer values with data from the authenticated customer in your frontend.
Here is an example script to get you started:
klaviyo.identify({
"$email" : customer.email,
"$first_name" : customer.first_name,
"$last_name" : customer.last_name
});Check your tracking
Test each snippet you install with an identified test profile. In Klaviyo, confirm that the expected Active on Site, Viewed Product, and Added to Cart events appear on that profile with the correct product and cart data. If you added the recently viewed products snippet, also check the Recently viewed products panel.
Add rewrite rules for product URLs
Your Magento 2 product catalog should sync normally with Klaviyo via our native integration, though if you are using a custom URL structure you will need to add some rewrite rules to your codebase.
Klaviyo builds Magento 2 product URLs using the following structure:
https://[YOUR STORE]/catalog/product/view/id/[PRODUCT ID]If your store is using a URL structure like:
https://[YOUR STORE]/products/[Product Name]Then add rewrite rules to your codebase to redirect the standard Magento 2 product links to your custom URL structure. Test a product link from your synced Klaviyo catalog and confirm that it opens the correct product on your headless storefront.
Additional resources
- Getting started with Magento 2.x (CE and EE)
Learn how to integrate Klaviyo with your Magento 2 CE or EE store. You'll need to install the Klaviyo extension in Magento, configure the extension and set up OAuth, then enable the integration in Klaviyo. This guide covers all required integration steps, as well as how to confirm your historical data sync is successful.
- Magento integration system requirements reference
Learn about the system requirements for optimal syncing with Magento 1 or 2. The administrator of your Magento store is responsible for system specifications and configuration. Ensuring that your system is configured to work with Klaviyo will enable a smooth integration experience.
- Magento 2 data reference
Learn what data Klaviyo imports from your Magento 2 store when you integrate the two platforms. Klaviyo's integration with Magento 2 pulls in all of the historical data in your Magento 2 store with the initial historic sync. Once enabled the integration will also begin to sync order and customer data every 30 minutes. Examples of this data include the information associated with past placed orders, fulfilled orders, etc.