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 🙏

© 2026 – Pkg Stats / Ryan Hefner

@polar-analytics/pixel-sdk

v0.15.0

Published

A JavaScript/TypeScript SDK for reporting customer touchpoints to Polar Analytics

Downloads

4,270

Readme

Pixel SDK

A lightweight JavaScript utility for reporting user touchpoints, similar to the Polar Analytics Pixel.

Contents

Installation

npm install @polar-analytics/pixel-sdk

Example usage

import {
  generatePayloadBase,
  sendPixelEvent,
  eventFactory,
} from "@polar-analytics/pixel-sdk";

const payloadBase = await generatePayloadBase({
  // Optional, include if available
  // customer: {
  //   id: <variable-containing-customer-id>,
  //   email: <variable-containing-customer-email>,
  // },
});

// An anonymous ID to identify the device + browser
// Please refer to https://community.shopify.com/c/shopify-apps/web-pixel-clientid/m-p/2664271/highlight/true#M80886
// As a fallback you can also use payloadBase.data.user_id.
const shopifyClientId =

// <the url of the shopify store> i.e. something.myshopify.com
const shopifyShopURL =

// Use the corresponding eventFactory for the desired event type.
const data = eventFactory.cart_viewed({
    shopifyEventId: crypto.randomUUID(),
    shopifyClientId,
    shopifyShopURL,
})

/* If you want to send a custom event not supported by the event factory,
   you can use this helper instead.

   Please only use this method if the event is not supported natively by
   the eventFactory. Using the custom event handler to send a non-custom
   supported event might result in sending incomplete data.

const data = eventFactory.custom({
  shopifyEventName: "<the-name-of-the-custom-event>",
  shopifyEventId: crypto.randomUUID(),
  shopifyClientId,
  shopifyShopURL,
})
*/

sendPixelEvent(
  pixelEndpoint /* obtained from polar analytics */,
  payloadBase,
  { data },
);

(Optional) With callbacks and retries

sendPixelEvent retries failed requests with exponential backoff (default: 3 retries) and returns a SendPixelEventResult.

const result = await sendPixelEvent(
  pixelEndpoint,
  payloadBase,
  { data },
  {
    maxRetries: 5,
    onSuccess: (response) => {
      console.log("Event delivered", response.status);
    },
    onError: (error, attempts) => {
      console.error(`Failed after ${attempts} attempts`, error);
    },
    onRetry: (attempt, error, nextDelayMs) => {
      console.warn(`Retry ${attempt} in ${nextDelayMs}ms`);
    },
  },
);

if (!result.success) {
  // result.error and result.attempts are available
}

(Optional) With sendBeacon (page unload)

Use useBeacon: true for page unload / visibilitychange scenarios. When the beacon fires successfully the function returns immediately with { success: true, usedBeacon: true }onSuccess/onError callbacks are not invoked. If the beacon fails, the SDK falls back to fetch with retries.

sendPixelEvent(pixelEndpoint, payloadBase, { data }, { useBeacon: true });

(Recommended) Cart Attribute Injection

Cart attributes persist tracking data (marketing cookies, UTM params, click IDs) through Shopify checkout, enabling accurate attribution.

The examples below use @shopify/storefront-api-client.

import {
  generateCartAttribute,
  POLAR_ATTR_KEY,
} from "@polar-analytics/pixel-sdk";
import { createStorefrontApiClient } from "@shopify/storefront-api-client";

const client = createStorefrontApiClient({
  storeDomain: "https://your-store.myshopify.com",
  apiVersion: "2025-04",
  publicAccessToken: "your-public-access-token",
});

Creating a cart with polar_attr

const result = await generateCartAttribute();

const { data } = await client.request(
  `mutation cartCreate($input: CartInput!) {
    cartCreate(input: $input) {
      cart { id attributes { key value } }
    }
  }`,
  {
    variables: {
      input: {
        lines: [{ merchandiseId: variantId, quantity: 1 }],
        attributes: [{ key: POLAR_ATTR_KEY, value: result.encoded }],
      },
    },
  },
);

Updating cart attributes (with merge)

When updating an existing cart, pass the current polar_attr value so first-touch attribution data is preserved:

const existingPolarAttr = cart.attributes.find(
  (a) => a.key === POLAR_ATTR_KEY,
)?.value;

const result = await generateCartAttribute({
  existingPolarAttr,
});

await client.request(
  `mutation cartAttributesUpdate($cartId: ID!, $attributes: [AttributeInput!]!) {
    cartAttributesUpdate(cartId: $cartId, attributes: $attributes) {
      cart { id attributes { key value } }
    }
  }`,
  {
    variables: {
      cartId: cart.id,
      attributes: [{ key: POLAR_ATTR_KEY, value: result.encoded }],
    },
  },
);

Best Practices

  • Call generateCartAttribute() on every cart mutation (create, add line, update). This ensures the latest session info is always attached.
  • Always pass existingPolarAttr on cart updates. This preserves first-touch attribution (e.g. the original gclid).

API Reference

Supported Events

eventFactory.page_viewed

The page_viewed event logs an instance where a customer visited a page. This event is available on the online store, checkout, and Order status pages.

Source: Shopify Documentation

eventFactory.product_viewed

The product_viewed event logs an instance where a customer visited a product details page. This event is available on the product page.

Source: Shopify Documentation

eventFactory.collection_viewed

The collection_viewed event logs an instance where a customer visited a product collection index page. This event is available on the online store page.

Source: Shopify Documentation

eventFactory.search_submitted

The search_submitted event logs an instance where a customer performed a search on the storefront. The products returned from the search query are in this event object (the first product variant for each product is listed in the array). This event is available on the online store page.

Source: Shopify Documentation

eventFactory.cart_viewed

The cart_viewed event logs an instance where a customer visited the cart page.

Source: Shopify Documentation

eventFactory.product_added_to_cart

The product_added_to_cart event logs an instance where a customer adds a product to their cart. This event is available on the online store page.

Source: Shopify Documentation

eventFactory.product_removed_from_cart

The product_removed_from_cart event logs an instance where a customer removes a product from their cart. This event is available on the online store page.

Source: Shopify Documentation

eventFactory.checkout_started

The checkout_started event logs an instance of a customer starting the checkout process. This event is available on the checkout page. For Checkout Extensibility, this event is triggered every time a customer enters checkout. For non-checkout extensible shops, this event is only triggered the first time a customer enters checkout.

Source: Shopify Documentation

eventFactory.checkout_address_info_submitted

The checkout_address_info_submitted event logs an instance of a customer submitting their mailing address. This event is only available in checkouts where Checkout Extensibility for customizations is enabled.

Source: Shopify Documentation

eventFactory.checkout_contact_info_submitted

The checkout_contact_info_submitted event logs an instance where a customer submits a checkout form. This event is only available in checkouts where Checkout Extensibility for customizations is enabled.

Source: Shopify Documentation

eventFactory.checkout_shipping_info_submitted

The checkout_shipping_info_submitted event logs an instance where the customer chooses a shipping rate. This event is only available in checkouts where Checkout Extensibility for customizations is enabled.

Source: Shopify Documentation

eventFactory.payment_info_submitted

The payment_info_submitted event logs an instance of a customer submitting their payment information. This event is available on the checkout page.

Source: Shopify Documentation

eventFactory.checkout_completed

The checkout_completed event logs when a visitor completes a purchase. It's triggered once for each checkout, typically on the Thank you page. However, for upsells and post purchases, the checkout_completed event is triggered on the first upsell offer page instead. The event isn't triggered again on the Thank you page. If the page where the event is supposed to be triggered fails to load, then the checkout_completed event isn't triggered at all.

Source: Shopify Documentation

eventFactory.custom

Use if you want to track something not covered by the standard events listed above.

For SDK developers

How to deploy a new version

  1. Make the changes you want to make, try to be backwards compatible when possible
  2. Create a CHANGELOG.md entry using npx changeset
  3. Deploy to NPM using yarn deploy (You need access to the NPM 2FA)
  4. Commit and merge the changes.
  5. Update the Polar Shopify Extension to use the latest version of the SDK
  6. (If relevant) inform third-parties using the SDK that there is value in updating.