npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@frontend-sdk/klaviyo

v0.25.1

Published

Klaviyo integration for Shogun Frontend.

Downloads

113

Readme

Klaviyo

Klaviyo integration for Shogun Frontend.

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

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:

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

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