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

marketin-js

v1.0.1

Published

MarketIn SDK for affiliate and conversion tracking.

Downloads

23

Readme

MarketIn JavaScript SDK

A lightweight browser SDK for tracking affiliate activity, page views, and conversions with the MarketIn platform.

Installation options

CDN (recommended for quick embeds)

<script src="https://cdn.jsdelivr.net/gh/ayg3/sdk@latest/marketin-sdk.min.js"></script>
<script type="module">
  import { initMarketIn, trackConversion, trackPageView } from 'marketin-js'

  async function bootstrap() {
    await initMarketIn({
      brandId: 'YOUR_BRAND_ID',
      apiEndpoint: 'https://api.marketin.now/api/v1',
      debug: true
    })

    trackPageView()
  }

  bootstrap()
</script>

Important: The CDN script populates window.MarketIn. Load it before calling any helper exported by this package. The helpers poll window.MarketIn and no-op safely while waiting, but they can only work once the global SDK is available.

NPM package (bundler usage)

npm install marketin-js

Add the CDN <script> tag to your host page (or bundle the script yourself) and then import the helpers in your app:

import { initMarketIn, handleTrackConversion, handleSubscriptionSubmit, trackPageView } from 'marketin-js'

// Ensure the CDN script has run and window.MarketIn exists
await initMarketIn({ brandId: 'YOUR_BRAND_ID' })

trackPageView()

Initialization

Call initMarketIn once after the DOM has loaded:

await initMarketIn({
  brandId: 'acme-123',
  apiEndpoint: 'https://api.marketin.now/api/v1',
  debug: false,
  campaignId: 'cmp_789',
  affiliateId: 'aff_456'
})
  • brandId (required): Provided by MarketIn.
  • apiEndpoint: Override for non-production environments.
  • debug: Enables verbose console logging when true.
  • campaignId / affiliateId: Optional defaults if your page doesn’t include query params like ?aid= or ?cid=.

The underlying SDK automatically:

  • Generates a session ID if none exists.
  • Reads URL query parameters (aid, cid, pid, UTM tags, etc.).
  • Invokes trackPageView on init.
  • Persists click identifiers in cookies for de-duplication.

React / SPA example (Vite, CRA, Next.js)

For single-page apps, call initMarketIn inside a useEffect and preserve the attribution params across client-side navigation:

import { useEffect } from 'react'
import { initMarketIn } from 'marketin-js'

export function App() {
  useEffect(() => {
    const bootstrap = async () => {
      await initMarketIn({
        brandId: import.meta.env.VITE_MARKETIN_BRAND_ID ?? 1,
        apiEndpoint: 'https://api.marketin.now/api/v1',
        debug: true,
      })
    }

    if (typeof window !== 'undefined') {
      bootstrap().catch((error) => {
        console.error('MarketIn init failed', error)
      })

      const { search, pathname } = window.location
      const params = new URLSearchParams(search)

      if (params.get('aid') || params.get('cid') || params.get('pid')) {
        sessionStorage.setItem('marketinParams', search)
      }

      const savedParams = sessionStorage.getItem('marketinParams')
      if (!search && savedParams) {
        window.history.replaceState({}, '', `${pathname}${savedParams}`)
      }
    }

    return undefined
  }, [])

  return <YourRoutes />
}
  • The CDN script must still run (e.g., added to index.html) so that window.MarketIn exists before this effect executes.
  • Attribution params (aid, cid, pid) are cached in sessionStorage and replayed after client-side route changes, ensuring conversions remain tied to the correct affiliate/campaign.

Tracking helpers

trackPageView(options?)

Logs a page view with optional overrides (url, referrer, campaignId, etc.). Defaults are derived from the browser environment and any query parameters present.

trackConversion(payload)

Posts purchase or subscription conversions to MarketIn using whatever billing data you collect on the client.

Prerequisites: initMarketIn (or MarketIn.init) must have already hydrated campaignId and affiliateId. If either is missing, the SDK skips the request and logs Conversion skipped.

One-off purchases (Paystack/Stripe success handlers)

import { trackConversion } from 'marketin-js'

trackConversion({
  eventType: 'purchase',              // any string not starting with "subscription"
  productId: 'plan-premium',          // required for non-subscription events
  value: paystackResponse.amount,     // numeric order total
  currency: paystackResponse.currency,
  conversionRef: paystackResponse.reference, // stable per transaction for de-dupe
  metadata: { paymentProvider: 'paystack' }
})
  • productId must be supplied for purchases or the call aborts.
  • Supply the billing provider's charge/transaction ID as conversionRef so retries stay idempotent. The SDK also stores this under localStorage key mi_conv_<sessionId>_<eventType> to suppress duplicates.
  • The payload automatically includes the current session, campaign, and affiliate IDs captured during initialization or via trackAffiliateClick.

Subscriptions (renewals, upgrades, cancellations)

import { trackConversion } from 'marketin-js'

trackConversion({
  eventType: 'subscription_renewed',  // must start with "subscription"
  subscriptionId: stripeSubscription.id,
  periodNumber: stripeInvoice.current_period,
  planId: stripeSubscription.plan?.id,
  interval: stripeSubscription.items.data[0]?.plan?.interval,
  recurringAmount: stripeInvoice.amount_paid,
  currency: stripeInvoice.currency,
  subscriptionStatus: stripeSubscription.status,
  conversionRef: stripeInvoice.id,
  metadata: { paymentProvider: 'stripe' }
})
  • When eventType begins with subscription, productId becomes optional; subscription context is forwarded in payload.metadata along with any extra fields you provide.
  • You can attach planId, interval, periodNumber, or custom metadata—everything is forwarded to MarketIn unchanged.

Client-only flow: These helpers rely on the browser environment (window, localStorage, cookies). Invoke them from the same client session that captured the affiliate click. Server-side webhooks should use a dedicated server integration instead.

handleTrackConversion(payload)

High-level helper for conversions:

handleTrackConversion({
  productId: 'prod-123',
  value: 199.99,
  currency: 'USD',
  conversionRef: 'order-456'
})

For subscription flows:

handleTrackConversion({
  eventType: 'subscription_renewed',
  recurringAmount: 49.99,
  currency: 'USD',
  subscriptionId: 'sub-789',
  planId: 'plan-monthly',
  interval: 'month',
  periodNumber: 2
})

handleSubscriptionSubmit(event)

Drop-in form handler for subscription conversions:

<form id="subscription" onsubmit="return false;">
  <input name="eventType" value="subscription_started" />
  <input name="recurringAmount" value="29.99" />
  <button type="submit">Subscribe</button>
</form>

<script type="module">
  import { handleSubscriptionSubmit } from 'marketin-js'

  document
    .getElementById('subscription')
    ?.addEventListener('submit', (event) => {
      const payload = handleSubscriptionSubmit(event)
      console.log('Tracked subscription', payload)
    })
</script>

The helper extracts form fields into a structured payload, calls handleTrackConversion, and returns the sanitized data.

Diagnostic utilities

  • onMarketInEvent(listener) – subscribe to internal SDK events (init, track_page_view, track_conversion, etc.).
  • isMarketInReady() – check whether the global SDK is available.
  • crawlPageData() – scrape meta/product tags from the page and forward them to MarketIn.

Browser requirements & SSR

  • This SDK relies on browser globals (window, document, fetch, localStorage). Guard any server-side rendering hooks by checking typeof window !== 'undefined'.
  • The helpers no-op gracefully when the SDK is unavailable, but you should still ensure the CDN script runs before invoking tracking functions.

Development scripts

npm install
npm run build

npm run build uses tsup to bundle ESM + CJS outputs with TypeScript definitions under dist/.


Need help integrating? Contact the MarketIn team or open an issue on the repository.