AxiTrace JavaScript SDK reference - install the browser pixel and start tracking visitor events on your website.

JavaScript SDK

Integrate AxiTrace into your website with our lightweight JavaScript SDK. Automatically track page views, user sessions, and custom events with full support for Meta/Facebook and TikTok Conversions API deduplication.

Critical: Read Before Implementing

Incorrect SDK installation is the #1 cause of tracking failures. The loading order and synchronicity of scripts directly impacts whether your events are tracked correctly, especially for users coming from Facebook/Instagram ads (In-App Browser).

Jump to Installation | Facebook In-App Browser Issues | Troubleshooting: 0% Coverage

Installation

There are two ways to install the SDK: synchronous (recommended) and asynchronous. The choice depends on whether you need to track events immediately in the <head> section.

Option 1: Synchronous Loading (Recommended)

Use this method when:

  • You track events (like product.view) in the <head> section
  • You want maximum reliability for Facebook/Instagram In-App Browser users
  • You need events to fire before users potentially leave the page
Why Synchronous?

The SDK is only ~11KB gzipped (~37KB uncompressed) - smaller than most images on your page. Synchronous loading adds minimal latency (~50-100ms) but guarantees the SDK is ready when your tracking code runs. This is critical for capturing users who leave quickly (bounce within 1-3 seconds), especially from Facebook/Instagram In-App Browser.

<head>
    <!-- ============================================================= -->
    <!-- RECOMMENDED: Load pixels BEFORE AxiTrace SDK                  -->
    <!-- SDK calls fbq()/ttq() with eventID for deduplication.         -->
    <!-- Since SDK 0.7.6 calls made before a pixel loads are queued    -->
    <!-- and replayed for up to 30s, so late pixels (e.g. loaded via   -->
    <!-- a tag manager) are bridged too - earlier loading just makes   -->
    <!-- the browser event fire sooner.                                -->
    <!-- ============================================================= -->

    <!-- 1. TikTok Pixel (init only, NO ttq.page()) -->
    <script>
        !function (w, d, t) {
            w.TiktokAnalyticsObject=t;var ttq=w[t]=w[t]||[];
            ttq.methods=["page","track","identify","instances","debug","on","off","once","ready","alias","group","enableCookie","disableCookie","holdConsent","revokeConsent","grantConsent"];
            ttq.setAndDefer=function(t,e){t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}};
            for(var i=0;i<ttq.methods.length;i++)ttq.setAndDefer(ttq,ttq.methods[i]);
            ttq.instance=function(t){for(var e=ttq._i[t]||[],n=0;n<ttq.methods.length;n++)ttq.setAndDefer(e,ttq.methods[n]);return e};
            ttq.load=function(e,n){var r="https://analytics.tiktok.com/i18n/pixel/events.js",o=n&&n.partner;
            ttq._i=ttq._i||{},ttq._i[e]=[],ttq._i[e]._u=r,ttq._t=ttq._t||{},ttq._t[e]=+new Date,ttq._o=ttq._o||{},ttq._o[e]=n||{};
            n=document.createElement("script");n.type="text/javascript",n.async=!0,n.src=r+"?sdkid="+e+"&lib="+t;
            e=document.getElementsByTagName("script")[0];e.parentNode.insertBefore(n,e)};

            ttq.load('YOUR_TIKTOK_PIXEL_ID');
            // REMOVED: ttq.page(); - AxiTrace SDK handles PageView with event_id for deduplication
        }(window, document, 'ttq');
    </script>

    <!-- 2. Facebook/Meta Pixel (init only, NO fbq('track', 'PageView')) -->
    <script>
        !function(f,b,e,v,n,t,s)
        {if(f.fbq)return;n=f.fbq=function(){n.callMethod?
        n.callMethod.apply(n,arguments):n.queue.push(arguments)};
        if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
        n.queue=[];t=b.createElement(e);t.async=!0;
        t.src=v;s=b.getElementsByTagName(e)[0];
        s.parentNode.insertBefore(t,s)}(window, document,'script',
        'https://connect.facebook.net/en_US/fbevents.js');
        fbq('init', 'YOUR_FB_PIXEL_ID');
        // REMOVED: fbq('track', 'PageView'); - AxiTrace SDK handles this with eventID
    </script>
    <noscript><img height="1" width="1" style="display:none"
        src="https://www.facebook.com/tr?id=YOUR_FB_PIXEL_ID&ev=PageView&noscript=1"/></noscript>

    <!-- 3. AxiTrace SDK - loaded SYNCHRONOUSLY after pixels -->
    <script src="https://axi.yourdomain.com/axitrack.js"></script>
    <script>
        Axitrace.init({
            apiUrl: 'https://axi.yourdomain.com',
            publicKey: 'pk_live_YOUR_PUBLIC_KEY'
        });
    </script>

    <!-- 4. Now you can track page-specific events (e.g., on product pages) -->
    <!-- This code would be in a template that extends your base layout -->
    <!--
    <script>
        Axitrace._instance.track('product.view', {
            sku: 'PRODUCT-SKU',
            name: 'Product Name',
            price: 99.99,
            currency: 'USD'
        });
    </script>
    -->

</head>

Option 2: Asynchronous Loading

Use this method when:

  • You only track events triggered by user actions (clicks, form submissions)
  • You don't need to track product.view immediately on page load
  • Page load performance is critical and you can accept potential tracking gaps
Warning: Async Loading Limitations

With async loading, the SDK may not be ready when your tracking code runs. Do NOT track events immediately after the script tag. Use the onload callback or wait for user interaction.

<!-- Load pixels FIRST (same as synchronous method) -->
<!-- ... TikTok Pixel ... -->
<!-- ... Facebook Pixel ... -->

<!-- AxiTrace SDK - Asynchronous Loading -->
<script>
(function() {
    var script = document.createElement('script');
    script.src = 'https://axi.yourdomain.com/axitrack.js';
    script.async = true;
    document.head.appendChild(script);

    script.onload = function() {
        Axitrace.init({
            apiUrl: 'https://axi.yourdomain.com',
            publicKey: 'pk_live_YOUR_PUBLIC_KEY'
        });

        // You CAN track events here in the onload callback
        // But this may be too late for users who bounce quickly!
    };
})();
</script>
Custom Tracking Domain

Replace axi.yourdomain.com with your custom tracking domain configured in Workspace settings → Tracking & domains. Using a custom subdomain helps avoid ad blockers and provides better first-party cookie support.

Facebook In-App Browser (Critical Issue)

When users click on your Facebook or Instagram ads, they open your website in the Facebook In-App Browser (also called Facebook WebView or FB_IAB). This browser has unique characteristics that can cause tracking failures:

The Problem

Up to 40% of Facebook ad traffic comes from users in the In-App Browser who:

  • Bounce within 1-3 seconds (swipe back to Facebook)
  • Close the browser before JavaScript at the end of <body> executes
  • Never trigger DOMContentLoaded or window.onload events

Result: If your product.view tracking is in <body>, these users will have PageView recorded but NOT ProductView, causing:

  • Inaccurate funnel data (inflated bounce rate)
  • Missing ViewContent events in Facebook Ads
  • Poor Custom Audience building (can't retarget product viewers)
  • Incorrect ROAS calculations

The Solution: Track in <head> with Synchronous SDK

Move page-specific event tracking to the <head> section, after the synchronously-loaded SDK:

<!-- base-layout.html (your master template) -->
<head>
    <!-- ... meta tags, CSS ... -->

    <!-- 1. Pixels (TikTok, Facebook) -->
    <!-- ... pixel code ... -->

    <!-- 2. AxiTrace SDK (synchronous) -->
    <script src="https://axi.yourdomain.com/axitrack.js"></script>
    <script>
        Axitrace.init({
            apiUrl: 'https://axi.yourdomain.com',
            publicKey: 'pk_live_YOUR_KEY'
        });
    </script>

    <!-- 3. Page-specific tracking block (overridden by child templates) -->
    {% block head_tracking %}{% endblock %}

</head>
<!-- product-page.html (extends base-layout) -->
{% extends 'base-layout.html' %}

{% block head_tracking %}
<script>
    // SDK is already loaded and initialized!
    // This runs IMMEDIATELY in <head>, before user can bounce
    Axitrace._instance.track('product.view', {
        sku: '{{ product.sku }}',
        name: '{{ product.name }}',
        price: {{ product.price }},
        currency: '{{ currency }}'
    });
</script>
{% endblock %}

Detecting Facebook In-App Browser

You can detect if a user is in the Facebook In-App Browser by checking the User-Agent:

function isFacebookInAppBrowser() {
    var ua = navigator.userAgent || navigator.vendor || window.opera;
    return ua.indexOf('FBAN') > -1 || ua.indexOf('FBAV') > -1 || ua.indexOf('FB_IAB') > -1;
}

// Example User-Agent from Facebook In-App Browser:
// Mozilla/5.0 (Linux; Android 14; ...) [FB_IAB/FB4A;FBAV/545.0.0.43.63;...]

Why PageView Works but ProductView Doesn't

Understanding the timing is critical:

Timing What Happens User in FB IAB
T+0ms HTML starts loading User sees loading...
T+50ms <head> scripts execute Still loading
T+100ms SDK init, PageView sent Still loading
T+500ms First paint, content visible User sees page
T+1000ms User swipes back to Facebook! User GONE
T+2000ms <body> end scripts execute Page already closed
T+2500ms DOMContentLoaded fires Never happens

Key insight: Scripts in <head> execute at T+50-100ms. Scripts at the end of <body> execute at T+2000ms+. Users who bounce at T+1000ms will have <head> events but NOT <body> events.

Initialization Options

Option Type Required Description
apiUrl string Yes Your custom tracking domain (e.g., https://axi.yourdomain.com)
publicKey string Yes Your workspace Public Key (starts with pk_live_)
workspaceId string No Optional workspace ID for debugging (starts with VT-). Not required for tracking.
enableDebug boolean No Enable console logging for debugging (default: false)
autoTrackPageViews boolean No Automatically track page views on init (default: true)
facebookPixel object No Meta/Facebook Pixel deduplication config. Set { enabled: false } to disable. Default: enabled.
tiktokPixel object No TikTok Pixel deduplication config. Set { enabled: false } to disable. Default: enabled.
respectDNT boolean No Respect the browser's Do Not Track setting (default: false). The effective value is this option OR the workspace-level "Respect browser Do Not Track" setting (admin panel → Workspace settings → Privacy & consent), which is also off by default, so a page passing false never overrides a workspace that asked for DNT to be respected.
requireConsent boolean No Hold the SDK back until the visitor grants marketing consent - no cookie, no storage entry, no request of any kind until then (default: false). Tighten-only: the effective gate is this option OR the workspace "Respect cookie consent" setting, so passing false never switches the workspace gate off. Passing true also suppresses the workspace policy request itself until a grant arrives. See the Cookie consent guide.
consentCookie string | object No The cookie your consent tool writes on accept, as a name or { name, value }. A bare name grants only on an accepting value (1, true, yes, allow, allowed, granted, accept, accepted, all); a CMP's own opaque blob is read as unknown and never as a grant. Only used while the gate is effectively on.
consentCategory string No Accepted for backward compatibility and ignored. Only marketing consent ever unlocks AxiTrace (Consent Mode v2 ad_storage + ad_user_data, WP Consent API marketing); analytics-only consent is never enough.
consentSignals string | array No 'auto' (default) arms every signal, or narrow it with an array of 'api', 'cookie', 'gcm', 'tcf', 'vendor'. 'api' is always on.
consentTcfPurposes array No Extra IAB TCF purposes this page requires (default: [1]). The list is unioned with the purposes AxiTrace always needs, 1 and 7, so a page can add a purpose but never drop one.
sessionTtlMinutes number No Session timeout in minutes. A new session is created after this period of inactivity (default: 30)
cookieDomain string No Domain for SDK cookies. Set to .yourdomain.com for cross-subdomain tracking (default: current domain)
There is no redditPixel option

The browser-pixel bridge covers Meta and TikTok only - those are the pixels the SDK calls with its own event ID so the browser and Conversions API copies deduplicate. Reddit has no equivalent option and the SDK never calls rdt().

Practical consequence: install the Reddit Pixel init-only, without rdt('track', 'PageVisit'). The init call alone writes the _rdt_uuid cookie, which the SDK reads and AxiTrace forwards as Reddit's user.uuid - the strongest match key Reddit accepts. A manual rdt('track', 'PageVisit') would ship an empty conversionId and be counted on top of the server-side PAGE_VISIT, i.e. every visit twice. See Reddit CAPI → Install the Reddit Pixel.

Core Methods

Axitrace.grant() / Axitrace.revoke() / Axitrace.hasConsent()

The cookie-consent API. grant() starts tracking, revoke() stops it and deletes AxiTrace's own cookies, hasConsent() reports the current state. A grant() made before axitrack.js has finished loading is queued and applied on initialisation, so it is safe to call from a consent banner's callback at any time. window.axitraceConsent.grant() is an equivalent alias. Full details in the Cookie consent guide.

revoke() is the withdrawal path and is worth wiring wherever your banner lets a visitor take their consent back. It stops the queue, the throttler and the cookie watchers, and deletes vt_vid, vt_sid, vt_uid, their storage mirrors, the queued events, the session-scoped entries (session, campaign, stored referrer) and any cached Microsoft customer id. Cookies belonging to other tools, such as _fbp, _fbc and _ttp, are left alone. A later grant() boots a new visitor rather than restoring the old one.

Before the SDK may boot

Since 0.12.0 the SDK does not boot straight from init(). It first asks the ingestion endpoint for the workspace privacy policy (GET /sdk-config?pk=..., 2 second timeout) and applies the effective flags: consent gate and DNT are each the page value OR the workspace value. Only then does it write anything.

  • Tracking calls made in the meantime are buffered in memory (up to 50) and replayed in order once the SDK boots, each keeping the timestamp it was made at.
  • If the policy cannot be established - a network error, a non-2xx, a malformed body, or an explicit "unknown" - the SDK fails closed: nothing is written or sent, and it retries at 5 s, 15 s and 45 s after init. After the last retry it stays inert for the rest of the page.
  • A page that sets requireConsent: true makes no request at all, not even the policy request, until a grant arrives.
  • The answer is cacheable for 5 minutes, so a workspace setting changed in the admin panel takes effect on your site within 5 minutes.

Axitrace.init(options)

Initialize the SDK with your configuration. Must be called before any other methods.

Axitrace.init({
    apiUrl: 'https://axi.yourdomain.com',
    publicKey: 'pk_live_YOUR_PUBLIC_KEY',
    enableDebug: false  // Set to true for development
});
Shorthand on the global (SDK 0.23.0 and later)

Axitrace.track(...), Axitrace.trackCustom(...), Axitrace.identify(...), Axitrace.trackPageView(...) and Axitrace.trackError(...) call the same method on Axitrace._instance with the same arguments and return what it returns, so consent and the privacy policy apply exactly as they do to a direct call. A call made before Axitrace.init() is kept (up to 50 calls) and replayed once init() has run. Every Axitrace._instance example on this page keeps working unchanged; use that form if your page may load an SDK older than 0.23.0.

Axitrace._instance.track(eventName, properties)

Track one of the supported events with optional properties. Use Axitrace._instance.track() for synchronous calls. The event name must be one of the types listed in the Events reference (or one of their accepted aliases) - the tracking endpoint rejects any other name with HTTP 400, and the rejection shows up in your workspace's Event feed, on the Errors tab. You can attach any additional properties you need to a supported event; they are stored with the event.

// Track a product view (use in <head> for FB IAB compatibility)
Axitrace._instance.track('product.view', {
    sku: 'PROD-123',
    name: 'Premium Widget',
    price: 99.99,
    currency: 'USD',
    category: 'Electronics'
});

// Track add to cart (can be in <body> as it's user-triggered)
Axitrace._instance.track('product.addToCart', {
    sku: 'PROD-123',
    name: 'Premium Widget',
    price: 99.99,
    quantity: 2
});

Lead products. form.submit, subscribe and start_trial accept a products array among their properties (and form.submit and subscribe a numeric value with its currency); the SDK sends them at the root of the request in the transaction line shape. A custom event takes products in its options. Products are optional and an invalid line never stops the event. See Leads: JavaScript SDK.

Axitrace._instance.identify(userId)

Identify a user and associate them with their actions. Call this when a user logs in or registers. The userId should be a unique identifier for the user - typically their email address.

Automatic Email Detection

If you pass an email address as the userId, the SDK automatically enables Facebook Advanced Matching - passing the email to Meta Pixel for improved event match quality. The SDK also auto-captures emails from form submissions and email input fields.

// Identify user with email (recommended - enables Facebook Advanced Matching)
Axitrace._instance.identify('john@example.com');

// Or identify with any unique user ID
Axitrace._instance.identify('user-12345');

Axitrace._instance.trackPageView(extra)

Manually track a page view. This is useful for Single Page Applications where you need to track route changes. The SDK automatically tracks page views on init when autoTrackPageViews is true (default), so you only need this for SPA route changes.

// Manual page view (for SPAs on route change)
Axitrace._instance.trackPageView({
    path: '/products/widget-123'
});

Custom Events

Define your own event names in the workspace's Custom events module and send them with one call. Strict pre-registration applies: an unknown name is sent once per session per name with a console warning, so define the name first.

// A registered conversion event: the throttle applies, the pixel bridge
// fires (when the definition carries a Meta or TikTok bridge name) and the
// conversion value fields attach from the options.
Axitrace._instance.track('quote_requested', { menu_name: 'Salad' }, {
    value: 149.50,
    currency: 'PLN',
    transaction_id: 'order-1001'
});

A definition can also carry no-code DOM triggers (a CSS selector plus click, hover or visible). Test them in place by opening YOUR OWN SITE with the URL flag ?axitrace_test=1: that tab sends nothing to /track and renders the in-page selector tester instead. See the full Custom Events reference.

E-commerce Tracking

Track the complete customer journey from product discovery to purchase.

Product View (Critical: Use in <head>)

Important: <head> Placement

product.view should be tracked in the <head> section for Facebook In-App Browser compatibility. See Facebook In-App Browser section above.

Axitrace._instance.track('product.view', {
    content_id: 'WIDGET-001',          // Required for Facebook
    content_name: 'Premium Widget',     // Required for Facebook
    content_type: 'product',            // Required for Facebook
    content_category: 'Widgets',
    sku: 'WIDGET-001',
    name: 'Premium Widget',
    price: 49.99,
    currency: 'USD',
    brand: 'WidgetCo'
});

Add to Cart

Axitrace._instance.track('product.addToCart', {
    content_id: 'WIDGET-001',
    content_name: 'Premium Widget',
    content_type: 'product',
    sku: 'WIDGET-001',
    name: 'Premium Widget',
    price: 49.99,
    quantity: 2,
    currency: 'USD',
    value: 99.98  // price * quantity
});

Begin Checkout

Axitrace._instance.track('begin_checkout', {
    currency: 'USD',
    value: 99.98,
    items: [
        {
            item_id: 'WIDGET-001',
            item_name: 'Premium Widget',
            price: 49.99,
            quantity: 2
        }
    ]
});

Complete Transaction

Axitrace._instance.track('transaction.charge', {
    transaction_id: 'TXN-12345',
    currency: 'USD',
    value: 99.98,
    tax: 8.00,
    shipping: 5.99,
    items: [
        {
            item_id: 'WIDGET-001',
            item_name: 'Premium Widget',
            price: 49.99,
            quantity: 2
        }
    ]
});

Pixel Deduplication (Meta & TikTok)

AxiTrace SDK automatically handles event deduplication between browser pixels (Meta Pixel, TikTok Pixel) and server-side Conversions APIs. This ensures each conversion is counted only once, improving your ROAS calculations and reducing cost per result by up to 20%.

Why Deduplication Matters

Meta recommends >75% event coverage for optimal ad performance. Without proper deduplication, events are counted twice (once from pixel, once from Conversions API), leading to inflated conversion numbers and incorrect ROAS calculations.

How It Works

  1. SDK generates a unique event_id for each event
  2. SDK calls the browser pixel with this event_id (e.g., fbq('track', 'PageView', {}, {eventID: 'uuid'}))
  3. SDK sends the same event_id to AxiTrace server
  4. Server forwards the event with event_id to Meta/TikTok Conversions API
  5. Meta/TikTok matches the events and counts the conversion only once
Loading order (SDK 0.7.6+)

Since SDK 0.7.6 the loading order no longer matters for correctness: bridge calls made before a pixel has loaded are queued and replayed the moment the pixel appears (for up to 30 seconds), with the same eventID - deduplication works regardless of which leg reaches Meta/TikTok first. This covers pixels injected late by tag managers (GTM) and consent tools. Loading the pixel base code before the SDK is still recommended so the browser event fires as early as possible.

On SDK 0.7.5 and older, pixels had to be loaded BEFORE the SDK - otherwise the bridge call was silently skipped and Events Manager showed 0% event coverage. See Troubleshooting: 0% Event Coverage for debugging steps.

Remove Manual Pixel Calls

When using AxiTrace SDK with deduplication enabled, you must remove manual pixel event calls from your website:

  • Remove: fbq('track', 'PageView') - SDK handles this automatically
  • Remove: ttq.page() - SDK handles this automatically
  • Keep: fbq('init', 'PIXEL_ID') - SDK needs this to call the pixel
  • Keep: ttq.load('PIXEL_ID') - SDK needs this to call the pixel

Supported Events

The SDK automatically maps AxiTrace events to platform-specific pixel events:

AxiTrace Event Meta Pixel Event TikTok Pixel Event
page.view PageView Pageview
product.view ViewContent ViewContent
product.addToCart AddToCart AddToCart
begin_checkout InitiateCheckout InitiateCheckout
add_payment_info AddPaymentInfo AddPaymentInfo
transaction.charge Purchase CompletePayment
form.submit Lead SubmitForm
search Search Search
subscribe Subscribe Subscribe

Marketing Attribution

The SDK automatically captures UTM parameters and advertising click IDs from the URL. These are persisted across page views and attached to all events.

Automatically Captured Parameters

Category Parameters
UTM Parameters utm_source, utm_medium, utm_campaign, utm_term, utm_content
Facebook/Meta fbclid, fbp, fbc
Google Ads gclid, gbraid, wbraid
TikTok ttclid, ttp
Microsoft/Bing msclkid
Other Platforms twclid, epik, li_fat_id, sccid (Snapchat's ScCid), rdt_cid, oppref

Click ID persistence

A purchase rarely happens on the landing page, so the SDK keeps each ad click ID it reads from the URL in a first-party cookie and attaches it to every later event (page views, product events, transactions and custom events) until the platform's click attribution window ends. The window counts from the first time the SDK saw that click, so revisiting a bookmarked ad URL does not extend it, and a bookmarked click older than the window is dropped instead of being reported as a new ad visit. With requireConsent nothing is stored before consent, and Axitrace.revoke() deletes these cookies.

Click ID Platform SDK cookie Kept for Platform cookie read as fallback
gclid, gbraid, wbraidGoogle Ads_gclid, _gbraid, _wbraid90 days-
ttclidTikTok_ttclid90 days-
msclkidMicrosoft Advertising_axi_msclkid90 days_uetmsclkid (UET tag)
twclidX_axi_twclid90 days_twclid (X pixel)
epikPinterest_axi_epik60 days_epik (Pinterest tag)
li_fat_idLinkedIn_axi_li_fat_id30 daysli_fat_id (Insight Tag)
ScCid (sent as sccid)Snapchat_axi_sccid28 days-
rdt_cidReddit_rdt_cid28 days-
opprefOpenAI Ads_oppref28 days-

The platform cookies in the last column belong to the platforms' own tags. The SDK only reads them, when neither the URL nor its own cookie has the click, and never writes or deletes them. The Facebook click is kept in Meta's own _fbc format for 90 days.

Cookie Watching (fbp, fbc, ttp)

Facebook and TikTok pixels set cookies (_fbp, _fbc, _ttp) that identify browsers for better conversion matching. The SDK automatically watches for these cookies and sends them to the server via profile.update events when they become available.

This is important because these cookies are set after the initial PageView event - the SDK's cookie watcher ensures they're captured even if the user doesn't trigger any other events.

Single Page Applications (SPA)

Automatic SPA Navigation Tracking

The SDK automatically detects SPA route changes by hooking into history.pushState, history.replaceState, popstate, and hashchange events. In most cases, no additional code is needed for page view tracking in SPAs.

If you need more control over page view tracking (e.g., to add custom properties), you can manually track page views on route changes:

import { useEffect } from 'react';
import { useLocation } from 'react-router-dom';

function App() {
    const location = useLocation();

    useEffect(() => {
        // Track page view on route change
        if (window.Axitrace && window.Axitrace._instance) {
            Axitrace._instance.trackPageView({
                path: location.pathname,
                search: location.search
            });
        }
    }, [location]);

    return (/* ... */);
}
// In your router/index.js
router.afterEach((to, from) => {
    if (window.Axitrace && window.Axitrace._instance) {
        Axitrace._instance.trackPageView({
            path: to.path,
            title: to.meta.title
        });
    }
});
// In _app.js or _app.tsx
import { useRouter } from 'next/router';
import { useEffect } from 'react';

function MyApp({ Component, pageProps }) {
    const router = useRouter();

    useEffect(() => {
        const handleRouteChange = (url) => {
            if (window.Axitrace && window.Axitrace._instance) {
                Axitrace._instance.trackPageView({ path: url });
            }
        };

        router.events.on('routeChangeComplete', handleRouteChange);
        return () => {
            router.events.off('routeChangeComplete', handleRouteChange);
        };
    }, [router.events]);

    return <Component {...pageProps} />;
}

Debugging

Enable debug mode to see SDK activity in the browser console:

Axitrace.init({
    publicKey: 'pk_live_YOUR_PUBLIC_KEY',
    apiUrl: 'https://axi.yourdomain.com',
    enableDebug: true  // Enable console logging
});

With debug mode enabled, you'll see logs like:

[AxiTrace SDK] Queued event { event: "page.view", ... }
[AxiTrace SDK] Called Facebook Pixel { event: "PageView", eventID: "a1b2c3...", params: {...} }
[AxiTrace SDK] Called TikTok Pixel { event: "Pageview", event_id: "a1b2c3...", params: {...} }
[AxiTrace SDK] Starting ad platform cookie watcher { timeoutMs: 10000, ... }
[AxiTrace SDK] New ad platform cookies detected, sending profile.update { newCookies: ["fbp"], ... }
[AxiTrace SDK] Updated Facebook advanced matching { pixelId: "...", hasEmail: true, ... }
Production Warning

Remember to disable enableDebug: true in production to avoid console spam and potential performance impact.

User Identification

The SDK manages user identification automatically:

  • vt_vid - A persistent visitor ID stored in localStorage + cookie (365 days)
  • vt_sid - A session ID that expires after 30 minutes of inactivity
  • vt_uid - Set when you call Axitrace._instance.identify(), or automatically when email is captured from forms

Automatic Email Capture

The SDK automatically captures email addresses from your website without any additional code:

  • Form submissions - When a form is submitted, the SDK scans for email fields and automatically calls identify()
  • Email input fields - The SDK monitors input[type="email"] and fields with "email" in their name/id, capturing the email when the user finishes typing (on blur/change)
  • Dynamic forms - Uses MutationObserver to detect forms added via JavaScript (SPA, AJAX-loaded content)

When an email is captured, the SDK also automatically sends a form.submit event and updates Facebook Advanced Matching data for improved event match quality.

Privacy: Sensitive Fields Are Never Captured

The SDK automatically excludes sensitive fields from form capture: passwords, credit card numbers, CVV codes, social security numbers, bank account details, and other PII. Only email addresses and non-sensitive form fields are collected.

Server-Side Visitor ID (Safari ITP Bypass)

Safari's Intelligent Tracking Prevention (ITP) limits JavaScript-created cookies to 7 days. AxiTrace automatically sets an HttpOnly server-side cookie that survives ITP, ensuring visitor identification persists for up to 2 years.

Browser Support

The SDK supports all modern browsers:

  • Chrome 60+
  • Firefox 55+
  • Safari 12+ (with ITP bypass)
  • Edge 79+
  • Opera 47+
  • Facebook In-App Browser (iOS & Android)
  • Instagram In-App Browser (iOS & Android)

The SDK uses the Fetch API with keepalive: true for reliable event delivery, even during page navigation and unload. Events are batched and queued with automatic retry on network failures.