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

insert-affiliate-js-sdk

v1.3.0

Published

![Version](https://img.shields.io/badge/version-1.0.0-brightgreen) ![Platform](https://img.shields.io/badge/platform-Web%20%7C%20Capacitor-blue) ![License](https://img.shields.io/badge/license-MIT-lightgrey)

Readme

Insert Affiliate JavaScript SDK

Version Platform License

The official JavaScript SDK for Insert Affiliate - track affiliate-driven purchases on web and hybrid applications.

What does this SDK do? It connects your web or Capacitor app to Insert Affiliate's platform, enabling you to track which affiliates drive subscriptions and automatically pay them commissions when users make purchases.

Table of Contents


🚀 Quick Start (5 Minutes)

Get up and running with minimal code to validate the SDK works.

Prerequisites

Supported Platforms

| Platform | Status | |----------|--------| | Capacitor (iOS / Android) | ✅ Fully tested | | Web Browsers | ✅ Tested in modern browsers | | Other JS Environments | ⚠️ May work, not officially tested |

Installation

npm install insert-affiliate-js-sdk

For Capacitor apps, also run:

npx cap sync

Your First Integration

import { InsertAffiliate } from 'insert-affiliate-js-sdk';

// Initialize with verbose logging for setup
await InsertAffiliate.initialize('YOUR_COMPANY_CODE', true);

Expected Console Output:

[Insert Affiliate] SDK initialized with company code: YOUR_COMPANY_CODE
[Insert Affiliate] [VERBOSE] SDK marked as initialized

If you see these logs, the SDK is working! Now proceed to Essential Setup.

⚠️ Disable verbose logging in production by setting the second parameter to false.


⚙️ Essential Setup

Complete these three steps to start tracking affiliate-driven purchases.

1. Initialize the SDK

Add SDK initialization to your main entry point (main.ts, main.js, or App.tsx):

import { InsertAffiliate } from 'insert-affiliate-js-sdk';

await InsertAffiliate.initialize('YOUR_COMPANY_CODE');
// Full initialization with all options
await InsertAffiliate.initialize(
  'YOUR_COMPANY_CODE',   // Company code (required)
  true,                  // Enable verbose logging (optional, default: false)
  86400000,              // Attribution timeout in milliseconds (optional, e.g., 24 hours)
  true                   // Prevent affiliate transfer (optional, default: false)
);

Parameters:

  • companyCode (required): Your Insert Affiliate company code
  • verboseLogging (optional): Enable detailed console logs for debugging
  • affiliateAttributionActiveTime (optional): Time in milliseconds before attribution expires (e.g., 86400000 for 24 hours)
  • preventAffiliateTransfer (optional): When true, prevents a new affiliate link from overwriting an existing affiliate attribution (defaults to false)
    • Use this to ensure the first affiliate who acquired the user always gets credit
    • New affiliate links will be silently ignored if the user already has an affiliate

Verbose logging shows:

  • Initialization process and company code validation
  • Deep link processing and short code detection
  • API communication details
  • Storage operations

2. Configure Payment Verification

Choose the payment method(s) that match your platform:

| Method | Best For | Setup Guide | |--------|----------|-------------| | RevenueCat | Mobile IAP (iOS/Android) | View | | Stripe | Web-based payments | View | | Both | Hybrid apps with mobile + web payments | Set up both |

For mobile in-app purchases via Capacitor.

Step 1: Code Setup

import { InsertAffiliate } from 'insert-affiliate-js-sdk';
import { Purchases } from '@revenuecat/purchases-capacitor';

window.addEventListener('DOMContentLoaded', async () => {
  await InsertAffiliate.initialize(
    'YOUR_COMPANY_CODE',
    false,    // verbose logging
    86400000, // 24 hour attribution timeout (optional)
    true      // prevent affiliate transfer (optional)
  );
  await Purchases.configure({ apiKey: 'YOUR_REVENUECAT_API_KEY' });

  // Set up callback for when affiliate identifier changes
  // Note: Use preventAffiliateTransfer in initialize() to block affiliate changes in the SDK
  InsertAffiliate.setInsertAffiliateIdentifierChangeCallback(async (identifier, offerCode) => {
    if (!identifier) return;

    // Ensure RevenueCat subscriber exists before setting attributes
    const customerInfo = await Purchases.getCustomerInfo();

    // OPTIONAL: Prevent attribution for existing subscribers
    // Uncomment to ensure affiliates only earn from users they actually brought:
    // const hasActiveEntitlement = Object.keys(customerInfo.entitlements.active).length > 0;
    // if (hasActiveEntitlement) return; // User already subscribed, don't attribute

    // Get expiry timestamp for RevenueCat targeting
    const expiryTimestamp = await InsertAffiliate.getAffiliateExpiryTimestamp();

    // Set attributes for RevenueCat
    const attributes = {
      insert_affiliate: identifier,
      insert_timedout: expiryTimestamp?.toString() || '',
    };

    // Add offer code for RevenueCat Targeting (if available)
    if (offerCode) {
      attributes.affiliateOfferCode = offerCode;
    }

    await Purchases.setAttributes(attributes);
    await Purchases.syncAttributesAndOfferingsIfNeeded();
  });
});

Using RevenueCat Targeting (Recommended)

RevenueCat Targeting automatically shows different offerings based on the affiliateOfferCode attribute. Simply display offerings.current:

const offerings = await Purchases.getOfferings();
const currentOffering = offerings.current;
// RevenueCat targeting automatically shows the correct offering based on affiliateOfferCode

Step 2: Webhook Setup

  1. In RevenueCat, create a new webhook
  2. Configure webhook settings:
    • Webhook URL: https://api.insertaffiliate.com/v1/api/revenuecat-webhook
    • Event Type: "All events"
  3. In your Insert Affiliate dashboard:
    • Set In-App Purchase Verification to RevenueCat
    • Copy the RevenueCat Webhook Authentication Header value
  4. Paste the authentication header into RevenueCat's Authorization header field

RevenueCat setup complete!

For web-based subscriptions and payments.

Step 1: Connect Stripe Account

  1. Go to your Insert Affiliate dashboard settings
  2. Select Stripe as your verification method
  3. Click Connect with Stripe to authorize via Stripe Connect

Step 2: Pass Affiliate Data to Checkout

import { InsertAffiliate } from 'insert-affiliate-js-sdk';

const affiliateId = await InsertAffiliate.returnInsertAffiliateIdentifier();
const companyId = await InsertAffiliate.returnCompanyId();

const response = await fetch('/create-checkout-session', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    priceId: 'price_xxxxx',
    insertAffiliate: affiliateId,
    insertAffiliateCompanyId: companyId,
    successUrl: window.location.origin + '/success',
    cancelUrl: window.location.origin + '/canceled',
  }),
});

Step 3: Store in Stripe Metadata (Backend)

const session = await stripe.checkout.sessions.create({
  mode: 'subscription',
  line_items: [{ price: priceId, quantity: 1 }],
  metadata: {
    insertAffiliate: insertAffiliate || '',
    insertAffiliateCompanyId: insertAffiliateCompanyId || '',
  },
  subscription_data: {
    metadata: {
      insertAffiliate: insertAffiliate || '',
      insertAffiliateCompanyId: insertAffiliateCompanyId || '',
    },
  },
  success_url: successUrl,
  cancel_url: cancelUrl,
});

📖 View complete Stripe integration guide →

Includes:

  • Stripe Billing with RevenueCat
  • RevenueCat Web Billing integration
  • RevenueCat Web Purchase Links
  • Callback-based integration

Stripe setup complete!


3. Set Up Deep Linking

Deep linking lets affiliates share unique links that track users to your app/website.

| Provider | Best For | Complexity | |----------|----------|------------| | Insert Links | Simplest setup, no 3rd party | Simple | | Branch.io | Robust attribution | Medium | | AppsFlyer | Enterprise analytics | Medium |

Insert Links is Insert Affiliate's built-in deep linking - no configuration needed for web.

The SDK automatically:

  1. Detects insertAffiliate parameter from URLs
  2. Validates and stores the affiliate identifier
  3. Triggers callbacks when affiliate changes

That's it! Just initialize the SDK and affiliate links work automatically.

Learn more: Insert Links Documentation

For web redirects: Configure your Branch.io Quick Links to redirect to your web URL with the affiliate parameter:

https://yourwebsite.com/checkout?insertAffiliate={affiliateShortCode}

For Capacitor apps: Use the Branch.io Capacitor plugin:

import { BranchDeepLinks } from 'capacitor-branch-deep-links';
import { InsertAffiliate } from 'insert-affiliate-js-sdk';

BranchDeepLinks.addListener('init', async (event) => {
  const clicked = event?.referringParams?.['+clicked_branch_link'];
  const referringLink = event?.referringParams?.['~referring_link'];

  if (clicked && referringLink) {
    await InsertAffiliate.setInsertAffiliateIdentifier(referringLink);
  }
});

📖 View complete deep linking guide →

Configure your AppsFlyer OneLinks to redirect to your web URL with the affiliate parameter:

https://yourwebsite.com/checkout?insertAffiliate={affiliateShortCode}

The SDK automatically detects insertAffiliate from the URL and attributes the payment.

📖 View complete deep linking guide →


✅ Verify Your Integration

Integration Checklist

  • [ ] SDK Initializes: Check console for SDK initialized with company code log
  • [ ] Affiliate Detected: Visit your site with ?insertAffiliate=TEST123 and verify it's captured
  • [ ] Payment Tracked: Make a test purchase and verify it appears in Insert Affiliate dashboard

Testing URL Parameters

Visit your app with an affiliate parameter:

https://yourwebsite.com?insertAffiliate=TEST123

Check the affiliate was captured:

const affiliateId = await InsertAffiliate.returnInsertAffiliateIdentifier();
console.log('Detected affiliate:', affiliateId); // Should output: TEST123

Common Setup Issues

| Issue | Solution | |-------|----------| | "Company code not set" | Ensure initialize() is called before other SDK methods | | Affiliate not detected | Check URL parameter is exactly insertAffiliate (case-sensitive) | | Payment not tracked | Verify Stripe/RevenueCat webhook is configured correctly |


🔧 Advanced Features

Track custom events beyond purchases to incentivize affiliates for specific actions.

import { InsertAffiliate } from 'insert-affiliate-js-sdk';

// Track a signup event (affiliate identifier must be set first)
await InsertAffiliate.trackEvent('user_signup');

Use Cases:

  • Pay affiliates for signups instead of purchases
  • Track trial starts or content unlocks

Short codes are unique, 3-25 character alphanumeric identifiers that affiliates can share (e.g., "SAVE20" in a TikTok description).

Validate and Store Short Code:

const isValid = await InsertAffiliate.setShortCode('SAVE20');

if (isValid) {
  alert('Affiliate code applied!');

  // Check for associated offer
  const offerCode = await InsertAffiliate.getOfferCode();
  if (offerCode) {
    alert(`You unlocked: ${offerCode}`);
  }
} else {
  alert('Invalid affiliate code');
}

Get Affiliate Details Without Setting:

const details = await InsertAffiliate.getAffiliateDetails('SAVE20');

if (details) {
  console.log('Affiliate Name:', details.affiliateName);
  console.log('Short Code:', details.affiliateShortCode);
  console.log('Deep Link:', details.deeplinkUrl);
}

Learn more: Short Codes Documentation

Get notified when the affiliate identifier changes:

InsertAffiliate.setInsertAffiliateIdentifierChangeCallback((identifier, offerCode) => {
  if (identifier) {
    console.log('Affiliate changed:', identifier);
    console.log('Offer code:', offerCode || 'none');

    // Update UI
    document.getElementById('affiliate-banner').style.display = 'block';

    // Track in analytics
    analytics.track('affiliate_link_clicked', { identifier, offerCode });
  }
});

// Clear callback when done
InsertAffiliate.setInsertAffiliateIdentifierChangeCallback(null);

Callback Parameters:

  • identifier (string | null): The full affiliate identifier (shortCode-userId)
  • offerCode (string | null): The offer code associated with this affiliate (if any)

Prevent Affiliate Transfer

By default, clicking a new affiliate link will overwrite any existing attribution. Enable preventAffiliateTransfer to lock the first affiliate:

await InsertAffiliate.initialize(
  "YOUR_COMPANY_CODE",
  false,   // verboseLogging
  604800,  // 7-day attribution timeout
  true     // preventAffiliateTransfer - locks first affiliate
);

How it works:

  • When enabled, once a user is attributed to an affiliate, that attribution is locked
  • New affiliate links will not overwrite the existing attribution
  • The callback still fires with the existing affiliate data (not the new one)
  • Useful for preventing "affiliate stealing" where users click competitor links

Learn more: Prevent Affiliate Transfer Documentation


📖 API Reference

Core Methods

| Method | Description | Returns | |--------|-------------|---------| | initialize(companyCode, verbose?, timeout?, preventTransfer?) | Initialize the SDK | Promise<void> | | returnInsertAffiliateIdentifier(ignoreTimeout?) | Get current affiliate identifier | Promise<string \| null> | | returnCompanyId() | Get company ID | Promise<string \| null> | | setInsertAffiliateIdentifier(link) | Set affiliate from deep link | Promise<string \| null> | | setShortCode(code) | Validate and store short code | Promise<boolean> | | getAffiliateDetails(code) | Get affiliate info without storing | Promise<AffiliateDetails \| null> | | trackEvent(eventName) | Track custom event | Promise<void> | | getOfferCode() | Get offer code modifier | Promise<string \| null> | | getAffiliateExpiryTimestamp() | Get Unix timestamp (ms) when attribution expires | Promise<number \| null> | | getAffiliateStoredDate() | Get ISO date string when affiliate was stored | Promise<string \| null> | | isAffiliateAttributionValid() | Check if attribution is still valid | Promise<boolean> | | setInsertAffiliateIdentifierChangeCallback(fn) | Set change callback | void |

returnInsertAffiliateIdentifier(ignoreTimeout?)

Retrieves the current affiliate identifier.

Parameters:

  • ignoreTimeout (optional, boolean): Set to true to get identifier even if attribution window expired

Returns: Promise<string | null>

// Respects attribution window
const affiliateId = await InsertAffiliate.returnInsertAffiliateIdentifier();

// Ignores attribution window
const affiliateIdAlways = await InsertAffiliate.returnInsertAffiliateIdentifier(true);

returnCompanyId()

Retrieves the company ID used during initialization.

Returns: Promise<string | null>

const companyId = await InsertAffiliate.returnCompanyId();

🔍 Troubleshooting

Initialization Issues

Error: "Company code not set"

  • Solution: Call initialize() before any other SDK methods

Deep Linking Issues

Problem: Affiliate parameter not detected

  • Solution: Ensure parameter name is exactly insertAffiliate (case-sensitive)
  • Initialize SDK before URL parameters are processed

Payment Tracking Issues

Problem: Purchases not appearing in dashboard

  • Solution: Verify webhook configuration in Stripe/RevenueCat
  • Check both insertAffiliate and insertAffiliateCompanyId are in metadata

Verbose Logging

Enable detailed logs to diagnose issues:

await InsertAffiliate.initialize('YOUR_COMPANY_CODE', true);

📚 Support


Need help? Check our documentation or contact support.