🎩 You're Invited:Meet the Socket team at Black Hat in Las Vegas, August 3-6.RSVP
Sign In

@affitor/tracker

Package Overview
Dependencies
Maintainers
1
Versions
2
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@affitor/tracker

Affitor affiliate tracking SDK for JavaScript applications

latest
Source
npmnpm
Version
2.0.0
Version published
Maintainers
1
Created
Source

@affitor/tracker

Official JavaScript/TypeScript SDK for Affitor affiliate tracking. A Promise-based wrapper around the Affitor tracker script, inspired by @stripe/stripe-js.

Install

npm install @affitor/tracker

Entry Points

The SDK provides two entry points for different use cases:

Entry PointImportBest For
@affitor/trackerimport { loadAffitor } from '@affitor/tracker'Any JS/TS application
@affitor/tracker/reactimport { AffitorProvider, useAffitor } from '@affitor/tracker/react'React / Next.js apps

@affitor/tracker — Core SDK

loadAffitor(programId, options?)

Loads the Affitor tracker script and returns a Promise that resolves to the tracker instance.

  • Singleton — calling loadAffitor multiple times returns the same Promise
  • SSR-safe — resolves to null on the server
  • Guaranteed — the instance is always ready when the Promise resolves
import { loadAffitor } from '@affitor/tracker';

const affitor = await loadAffitor('59');

Options

OptionTypeDefaultDescription
env'production' | 'uat' | 'local''production'Environment preset (selects the tracker script URL)
debugbooleanfalseEnable debug mode (verbose console logs, cookie verification)
scriptUrlstringCustom script URL (overrides env preset)

Environment Presets

envScript URL
'production'https://api.affitor.com/js/affitor-tracker.js
'uat'https://uat-affitor-cms.vanilla-ott.com/js/affitor-tracker-uat.js
'local'http://localhost:1337/js/affitor-tracker-local.js
// Production (default)
const affitor = await loadAffitor('59');

// Local development with debug
const affitor = await loadAffitor('29', { env: 'local', debug: true });

// UAT
const affitor = await loadAffitor('29', { env: 'uat' });

// Custom URL (overrides env)
const affitor = await loadAffitor('29', { scriptUrl: 'https://my-cdn.com/tracker.js' });

Methods

Once loaded, the affitor instance provides these methods:

MethodDescription
signup(customerKey, email)Track a signup event. Takes the user's ID and email as positional args. Returns a Promise.
trackLead(data)Deprecated. Alias for signup(). Accepts { email, user_id }. Use signup() instead.
trackTest(data?)Send a test event to verify tracking is working.
redirectToCheckout(params)Redirect the user to the Affitor-powered checkout page.

Properties

PropertyTypeDescription
customerCodestring | nullThe affiliate customer code from cookie
affiliateUrlstring | nullThe affiliate referral URL from cookie
hasAffiliateAttributionbooleanWhether the current visitor was referred by an affiliate
debugModebooleanWhether debug mode is enabled
programIdnumberThe advertiser program ID

Example: Track Signup

import { loadAffitor } from '@affitor/tracker';

async function handleSignup(email: string, password: string) {
  // 1. Create the user account
  const { data } = await supabase.auth.signUp({ email, password });

  // 2. Track the signup — awaits script load, guaranteed to fire
  if (data.user) {
    const affitor = await loadAffitor('59');
    await affitor?.signup(data.user.id, data.user.email);
  }

  // 3. Navigate to dashboard
  router.push('/dashboard');
}

Example: Redirect to Checkout

import { loadAffitor } from '@affitor/tracker';

async function handleUpgrade() {
  const affitor = await loadAffitor('59');
  affitor?.redirectToCheckout({
    price: 19.99,
    programId: 59,
  });
}

@affitor/tracker/react — React Hooks

The React entry point provides two patterns: Provider + hook and standalone hook.

Pattern A: AffitorProvider + useAffitor()

Best when your whole app needs access to the tracker state (e.g. showing referral badges).

import { AffitorProvider, useAffitor } from '@affitor/tracker/react';

// 1. Wrap your app (layout.tsx or _app.tsx)
export default function RootLayout({ children }) {
  return (
    <AffitorProvider programId="59">
      {children}
    </AffitorProvider>
  );
}

// 2. Read tracker state in any component
function ReferralBadge() {
  const affitor = useAffitor();

  if (!affitor?.hasAffiliateAttribution) return null;

  return <span>Referred by a partner!</span>;
}

AffitorProvider Props

PropTypeRequiredDescription
programIdstring | numberYesYour Affitor program ID
debugbooleanNoEnable debug mode
scriptUrlstringNoCustom script URL

useAffitor()

Returns AffitorInstance | null. Returns null while the SDK is loading.

Important: useAffitor() is best for reading tracker state in the UI (e.g. hasAffiliateAttribution, customerCode). For critical tracking events like signup, use await loadAffitor() directly instead — see Which approach should I use? below.

Pattern B: useLoadAffitor() (Standalone)

Use this when you don't need a provider — the hook loads the SDK on mount.

import { useLoadAffitor } from '@affitor/tracker/react';

function MyComponent() {
  const affitor = useLoadAffitor('59', { debug: true });

  return (
    <div>
      {affitor?.hasAffiliateAttribution && <p>Partner referral detected</p>}
    </div>
  );
}

Which approach should I use?

For tracking events (signup, redirectToCheckout)

Always use await loadAffitor() directly. This guarantees the script is loaded before the event fires. Critical events must never be silently skipped.

// GOOD — guaranteed to fire
const affitor = await loadAffitor('59');
await affitor?.signup(userId, email);

// BAD — affitor could be null if script still loading
const affitor = useAffitor();
await affitor?.signup(userId, email); // silently skipped if null

For reading tracker state in UI

Use useAffitor() or useLoadAffitor(). If the value is null momentarily while loading, the UI simply doesn't render that part yet. No data is lost.

// GOOD — fine for UI, gracefully handles loading state
const affitor = useAffitor();
return affitor?.hasAffiliateAttribution ? <Badge /> : null;

Summary

Use CaseApproachWhy
signup on registrationawait loadAffitor()Must not be lost — awaits script load
redirectToCheckoutawait loadAffitor()Must not be lost — awaits script load
Show referral badge in UIuseAffitor()OK to show nothing while loading
Display customer codeuseAffitor()OK to show nothing while loading
Check hasAffiliateAttribution for conditional UIuseAffitor()OK to show nothing while loading

Migrating from Script Tag

If you're currently using the <script> tag approach:

Before (script tag)

<script src="https://api.affitor.com/js/affitor-tracker.js"
        data-affitor-program-id="59"></script>

<script>
  // Must check if loaded, use queue fallback, handle timing manually
  if (window.affitor) {
    window.affitor.trackLead({ email, user_id });
  } else {
    window.affitorQueue = window.affitorQueue || [];
    window.affitorQueue.push(['trackLead', { email, user_id }]);
  }
</script>

After (npm SDK)

import { loadAffitor } from '@affitor/tracker';

// No timing issues — awaits script load automatically
const affitor = await loadAffitor('59');
await affitor?.signup(userId, email);

No more:

  • Manual if (window.affitor) checks
  • Queue fallback code (affitorQueue.push)
  • Race conditions between script load and event firing
  • (window as any) type casting in TypeScript

API Reference

loadAffitor(programId, options?)

ParameterTypeDescription
programIdstring | numberYour Affitor program ID
options.env'production' | 'uat' | 'local'Environment preset
options.debugbooleanEnable debug mode
options.scriptUrlstringCustom script URL (overrides env)

Returns: Promise<AffitorInstance | null>

AffitorInstance

Method / PropertyTypeDescription
signup(customerKey, email)(customerKey: string, email: string) => Promise<void>Track a signup event
trackLead(data)(data: TrackLeadData) => voidDeprecated. Alias for signup().
trackTest(data?)(data?: TrackTestData) => voidSend test event
redirectToCheckout(params)(params: RedirectToCheckoutParams) => voidRedirect to checkout
customerCodestring | nullAffiliate customer code
affiliateUrlstring | nullAffiliate referral URL
hasAffiliateAttributionbooleanHas affiliate attribution
debugModebooleanDebug mode enabled
programIdnumberProgram ID

TrackLeadData

FieldTypeRequiredDescription
emailstringYesUser's email
user_idstringYesYour app's user ID (critical for payment attribution)
additional_dataRecord<string, unknown>NoExtra metadata

TrackTestData

FieldTypeRequiredDescription
step_idstringNoStep identifier (default: 'pageview')
messagestringNoTest message
user_idstringNoUser ID

RedirectToCheckoutParams

FieldTypeRequiredDescription
pricenumberNoPrice amount
programIdstring | numberNoOverride program ID

License

MIT

Keywords

affitor

FAQs

Package last updated on 17 Mar 2026

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts