Klaviyo

Klaviyo integration for Shogun Frontend.

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

⚠️ This package runs on Shogun Frontend and is in customer Beta. It might not currently support all ecommerce platforms or cover all use cases.

Klaviyo website →

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.

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:

    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.

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

    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 and not load Klaviyo's script (improving performance).

It can utilize:

  • either Klaviyo's signup page (https://manage.kmail-lists.com/subscriptions/subscribe)

    <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://manage.kmail-lists.com/ajax/subscriptions/subscribe)

    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
import { identifyUser, trackVisitedProduct, trackAddedToCart } from '@frontend-sdk/klaviyo'

const Component: React.FC<Props> = ({ siteId }) => {
  useKlaviyo(siteId) /* Klaviyo's script should be loaded */
  identifyUser({ $email: '[email protected]' }) /* 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, 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:

nametypedescription
siteIdrequiredKlaviyo ID of site
emailrequireduser email
productrequiredproduct ID
variantrequiredvariant ID
platformrequired'shopify' or 'bigcommerce'
shouldSubscribeoptional(boolean) whether to additionally subscribe to a newsletter
listIdoptionalKlaviyo ID of the newsletter to subscribe

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

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:

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


Did this page help you?