npm package: @frontend-sdk/klaviyo
Description: Klaviyo integration for Shogun Frontend.
Author: Shogun
Latest version: 0.25.1

# Klaviyo

Klaviyo integration for Shogun Frontend.

> Klaviyo is an email marketing platform created for online businesses — featuring powerful email and SMS marketing automation.

<table>
  <tbody>
    <tr>
      <td>⚠️</td>
      <td>This package runs on Shogun Frontend and is in customer Beta. It might not currently support all ecommerce platforms or cover all use cases.</td>
    </tr>
  </tbody>
</table>

[Klaviyo website →](https://www.klaviyo.com)

## Installation

`yarn add @frontend-sdk/klaviyo`

`npm install @frontend-sdk/klaviyo`

## Background

`@frontend-sdk/klaviyo` covers the following use-cases/features:

- display signup forms (both popup and embedded) designed in the Klaviyo app
- subscribe to notification for an out-of-stock product
- tracking for arbitrary events as well as for "visited product" and "added to cart" events

> 📘
>
> With `@frontend-sdk/klaviyo`, you don't need to add manually any snippet stated in [Klaviyo's documentation](https://help.klaviyo.com/hc/en-us/articles/115005080407-How-to-Integrate-with-Shopify#add-web-tracking-to-your-shopify-store4).

## Signup Forms

In Klaviyo, you can design a signup form to collect users into subscription lists.

1. Inject Klaviyo's script with your site ID:

   ```jsx
   import { useKlaviyo } from '@frontend-sdk/klaviyo'

   const App = () => {
   	useKlaviyo('<Klaviyo site ID>')
   	return …
   }
   ```

2. Popup forms will be displayed automatically based on their rules.

3. For embedded forms, add a `div` with form ID where you want this form to be displayed.

   ```html
   <div class="klaviyo-form-Abc123"></div>
   <!-- Abc123 — form id -->
   ```

4. There is a known problem when embedded forms are not displayed when a user navigates to a page with an already loaded script. To fix that, there is a hacky solution.

   You need to use a different hook (`useKlaviyoForceReload`) to inject script each time you need to show embedded form.

   _Take a note that if you want to use this hook, use it in all places instead of `useKlaviyo`._

   ```jsx
   import { useKlaviyoForceReload } from '@frontend-sdk/klaviyo'

   const Footer = () => {
     useKlaviyoForceReload('<Klaviyo site ID>')
     return (
       <>
         {/* … */}
         <div class="klaviyo-form-Abc123"></div> {/* Abc123 — form id */}
         {/* … */}
       </>
     )
   }
   ```

### Custom embedded signup forms

You can also [make custom signup forms](https://help.klaviyo.com/hc/en-us/articles/115005080167-How-to-Redirect-Existing-Signup-Forms-to-Klaviyo) and not load Klaviyo's script (improving performance).

It can utilize:

- either Klaviyo's [signup page](https://help.klaviyo.com/hc/en-us/articles/115005080167-How-to-Redirect-Existing-Signup-Forms-to-Klaviyo#redirecting-a-custom-form-to-klaviyo2) (`https://manage.kmail-lists.com/subscriptions/subscribe`)

  ```jsx
  <form action="https://manage.kmail-lists.com/subscriptions/subscribe" method="POST">
    <input type="hidden" name="g" value={listId} />
    <input type="email" name="email" placeholder="Email" />
    <button type="submit">Subscribe to newsletter</button>
  </form>
  ```

- or Klaviyo's [API endpoint](https://help.klaviyo.com/hc/en-us/articles/115005080167-How-to-Redirect-Existing-Signup-Forms-to-Klaviyo#using-a-klaviyo-subscribe-url-for-a-third-party-signup-form4) (`https://manage.kmail-lists.com/ajax/subscriptions/subscribe`)

  ```jsx
  const emailRef = useRef(null)
  const firstNameRef = useRef(null)
  const lastNameRef = useRef(null)
  const onSubmit = (event) => {
    event.preventDefault()
    const email = emailRef.current?.value
    const firstName = firstNameRef.current?.value
    const lastName = lastNameRef.current?.value
    const data = {
      g: listId,
      email: email ?? '',
      $fields: '$first_name,$last_name',
      $first_name: firstName ?? '',
      $last_name: lastName ?? '',
    }
    const urlData = new URLSearchParams(data)
    fetch(`https://manage.kmail-lists.com/ajax/subscriptions/subscribe`, {
      method: 'POST',
      body: urlData,
    })
  }
  return (
    <form onSubmit={onSubmit}>
      <input type="email" name="email" placeholder="Email" ref={emailRef} />
      <input type="text" name="firstName" placeholder="First Name" ref={firstNameRef} />
      <input type="text" name="lastName" placeholder="Last Name" ref={lastNameRef} />
      <button type="submit">Subscribe to newsletter</button>
    </form>
  )
  ```

## Tracking

To use Klaviyo's tracking, just use one of the provided functions:

- `identifyUser(userData)` — to identify user, must be called before other functions to track properly
- `trackEvent(name, eventData)` — to track arbitrary event with custom name
- `trackRecentlyViewedItem(product)` — to track product as recently viewed
- `trackVisitedProduct(product)` — to track "Visited Product" event
- `trackAddedToCart(product)` — to track "Added to Cart" event

```typescript jsx
import { identifyUser, trackVisitedProduct, trackAddedToCart } from '@frontend-sdk/klaviyo'

const Component: React.FC<Props> = ({ siteId }) => {
  useKlaviyo(siteId) /* Klaviyo's script should be loaded */
  identifyUser({ $email: 'user@email.local' }) /* identify user before tracking events */
  return (
    <>
      <button type="button" onClick={() => trackVisitedProduct(product)}>
        visit product
      </button>
      <button type="button" onClick={() => trackAddedToCart(product)}>
        add to cart
      </button>
    </>
  )
}
```

## Back-in-Stock

If a product is out-of-stock, the user may want to be notified when it is back in stock.

For that purpose, Klaviyo has a back-in-stock flow. You need to add integration to your store (Shopify or BigCommerce) in the Klaviyo.

Klaviyo then collects emails for each product separately, and when inventory for such product, increases it notifies users.

### Klaviyo's script

Klaviyo has a script that can detect if a product on a page is out-of-stock and automatically adds the "Notify me" button that opens a modal form to enter an email.

Unfortunately, such use case has limitations:

- for Shopify in all products should have `/products/` in their path
- for Shopify product should have and access to Shopify's `product.js` JSON to get information about inventory
- for BigCommerce product page should have a `form` with `action={`//${location.hostname}/cart.php`}` and inside an `input` with `name="product_id" value=<product id>`
- for BigCommerce product page should have `meta` tag with `property="og:type" content="product"`
- behavior is limited to a custom button that appears in the form if a product is out-of-stock; on click it opens a modal form that collects email
- customization is limited to Klaviyo's API (for [Shopify](https://help.klaviyo.com/hc/en-us/articles/360001895651-How-to-Install-Back-in-Stock-for-Shopify), for [BigCommerce](https://help.klaviyo.com/hc/en-us/articles/360025079491-How-to-Install-Back-In-Stock-for-BigCommerce))

### Using custom form

To overcome those limitations, it is better to create a custom form for collecting email and control when it should be shown.

To send data on this form submit we provide a `subscribeToBackInStock()` function with following parameters:

| name              | type         | description                                                   |
| ----------------- | ------------ | ------------------------------------------------------------- |
| `siteId`          | **required** | Klaviyo ID of site                                            |
| `email`           | **required** | user email                                                    |
| `product`         | **required** | product ID                                                    |
| `variant`         | **required** | variant ID                                                    |
| `platform`        | **required** | `'shopify'` or `'bigcommerce'`                                |
| `shouldSubscribe` | optional     | (`boolean`) whether to additionally subscribe to a newsletter |
| `listId`          | optional     | Klaviyo ID of the newsletter to subscribe                     |

Example of a form with option to subscribe to a newsletter:

```jsx
import { subscribeToBackInStock } from '@frontend-sdk/klaviyo'

const Component = ({ siteId, listId, productId, variantId }) => {
  const [email, setEmail] = useState('')
  const [shouldSubscribe, setShouldSubscribe] = useState(false)
  const onSubmit = (event) => {
    event.preventDefault()
    subscribeToBackInStock({
      siteId,
      email,
      product: productId,
      variant: variantId,
      listId,
      shouldSubscribe,
      platform: 'shopify' /* or 'bigcommerce' */,
    })
  }
  return (
    <form onSubmit={onSubmit}>
      <input type="email" placeholder="Email" value={email} onChange={(e) => setEmail(e.target.value)} />
      <br />
      <input
        type="checkbox"
        id="newsletter"
        checked={shouldSubscribe}
        onChange={() => setShouldSubscribe(!shouldSubscribe)}
      />
      <label htmlFor="newsletter">Subscribe to newsletter</label>
      <br />
      <button type="submit">Notify me when available</button>
    </form>
  )
}
```

Or in case of no need of option to subscribe to a newsletter:

```jsx
import { subscribeToBackInStock } from '@frontend-sdk/klaviyo'

const Component = ({ siteId, productId, variantId }) => {
  const [email, setEmail] = useState('')
  const onSubmit = (event) => {
    event.preventDefault()
    subscribeToBackInStock({
      siteId,
      email,
      product: productId,
      variant: variantId,
      platform: 'shopify' /* or 'bigcommerce' */,
    })
  }
  return (
    <form onSubmit={onSubmit}>
      <input type="email" placeholder="Email" value={email} onChange={(e) => setEmail(e.target.value)} />
      <br />
      <button type="submit">Notify me when available</button>
    </form>
  )
}
```

# Examples

You can see usage examples in Storybook stories.

# Links

- Official [JS API](https://www.klaviyo.com/docs/javascript-api)
- Official [instructions on how to use custom embedded form](https://help.klaviyo.com/hc/en-us/articles/115005080167-How-to-Redirect-Existing-Signup-Forms-to-Klaviyo)
- Official instructions for the back-in-stock feature
  - [for Shopify](https://help.klaviyo.com/hc/en-us/articles/360001895651-How-to-Install-Back-in-Stock-for-Shopify)
  - [for BigCommerce](https://help.klaviyo.com/hc/en-us/articles/360025079491-How-to-Install-Back-In-Stock-for-BigCommerce)
- List of [`identify` properties](https://www.klaviyo.com/docs/http-api) for Klaviyo CRM
- Instructions for [tracking recently viewed products](https://help.klaviyo.com/hc/en-us/articles/360019921772-How-to-Insert-Recently-Viewed-Items-into-an-Email)
- Instructions for product tracking
  - [for Shopify](https://help.klaviyo.com/hc/en-us/articles/115005080407-Integrate-with-Shopify#add-web-tracking-to-your-shopify-store4)
  - [for BigCommerce](https://help.klaviyo.com/hc/en-us/articles/115005082547-Integrate-with-BigCommerce-Stencil-Theme#add-viewed-product-tracking3)
- Mentioning of custom back-in-stock setup ([1](https://community.klaviyo.com/integrations-39/back-in-stock-with-woocommerce-646), [2](https://community.klaviyo.com/integrations-39/custom-back-in-stock-form-shopify-925))