Intempt Docs
Developer DocsSDK

JavaScript SDK

Full API reference for IntemptJS — event tracking, user identification, consent, and product tracking in the browser.

JavaScript SDK

IntemptJS is a browser SDK for tracking user events, managing identities, and handling consent. All public methods are available on the global window.intempt object.

Place all SDK method calls inside a <script> tag at the bottom of the <body> element.

Installation

Add two snippets to your page <head>. The first creates a queue buffer so window.intempt.* works immediately; the second loads the SDK asynchronously.

<!-- 1. Queue stub — buffers calls until the SDK is ready -->
<script>
(function () {
  if (window.intempt) return;
  var queue = [], pending = [];
  var methods = ['identify','group','track','record','alias','consent',
                 'productAdd','productOrdered','productView','logOut',
                 'optIn','optOut','isUserOptIn','recommendation'];
  var stub = { _isStub: true, _queue: queue, _pendingPromises: pending };
  methods.forEach(function (m) {
    stub[m] = function () {
      var args = [].slice.call(arguments);
      if (m === 'recommendation') {
        return new Promise(function (resolve, reject) {
          pending.push({ resolve: resolve, reject: reject });
          queue.push({ method: m, args: args });
        });
      }
      queue.push({ method: m, args: args });
    };
  });
  window.intempt = stub;
})();
</script>

<!-- 2. Load the SDK asynchronously -->
<script
  async
  src="https://cdn.intempt.com/v1/intempt.min.js?organization=my-org&project=my-project&source=web-source&key=username.password">
</script>

Configuration Parameters

ParameterDescription
organizationOrganization identifier
projectProject identifier
sourceSource ID (sourceId) for data transmission
keyAPI credentials in username.password format
shopifyInclude to enable Shopify tracking
magentoInclude to enable Magento product detection
autocaptureWhich auto-tracking families run. On when omitted. false turns all off, or list the ones to keep, like autocapture=pageview,submit. See Choosing what it captures
pii_scrubbingInclude to redact email, phone and card-number shapes, and fields named like email, phone, password or ssn, from every event before it leaves the browser. Off unless set, because redaction can't be undone

Parameters are activated by presence — include with any non-empty value to enable, omit entirely to disable. Note: =0 and =false do not disable shopify or magento — only omitting the parameter entirely does.

Tracking is off on localhost. By default the SDK blocks all tracking on localhost / 127.0.0.1 and for bot/crawler user agents. If nothing appears while developing locally, that's expected — test on a real or staging domain.


Auto-Tracking

How this compares across SDKs: Autocapture and automatic events.

Autocapture is on by default on web. There's nothing to turn on. Once the SDK loads it records:

EventWhen it fires
Page viewOn first load and on every SPA route change (pushState, replaceState, back/forward)
Page exitWhen the visitor leaves, including time spent on the page
SessionStarted on first interaction and kept alive as the visitor engages
ClickAny element clicked on the page
Form changeAny form field value change
Form submitAny form submission, with each field's name

For clicks and form events the SDK captures useful context: element tag, id, classes, visible text, link target, CSS-selector path, and, on submit, the names of the form's fields.

Web SDK
On when the SDK loadsYes
Typed field valuesNever captured. Sent as ******** on change and on submit
Turn it off&autocapture=false for all of it, or &autocapture=pageview,submit to keep only some
Keep values outdoNotCapture per element, or pii_scrubbing for the whole page

Choosing what it captures

Auto-tracking is four families. All four are on by default.

FamilyEvents
pageviewView Page, Leave Page
clickClick On
inputChange On
submitSubmit On

List the families you want to keep:

<script
  async
  src="https://cdn.intempt.com/v1/intempt.min.js?organization=my-org&project=my-project&source=web-source&key=username.password&autocapture=pageview,submit">
</script>

An unknown name is ignored and logged as a console warning. If none of the names you list is valid, nothing is auto-tracked, because you were trying to narrow it.

Sessions aren't a family and always run. Shopify and Magento aren't families either. They're commerce integrations, off until you add &shopify=1 or &magento=1, and autocapture never affects them.

Turning auto-tracking off

<script
  async
  src="https://cdn.intempt.com/v1/intempt.min.js?organization=my-org&project=my-project&source=web-source&key=username.password&autocapture=false">
</script>

Page views, page exits, clicks and form events stop. Sessions keep running, and track(), record() and every other explicit call still deliver.

This is not the same as optOut(). Opting a visitor out stops everything, explicit calls included.

What a visitor types is never captured

Text, email, number, date and every other typed input, textareas and contenteditable regions come through as ********, on change and on submit. A pre-filled value attribute is masked too. The field's name is kept, so you can still see which fields a form has.

Choices aren't typed, so a checkbox, radio or select value still comes through, and so does a button's label.

There's no switch to capture typed values. To send one on purpose, pass it in a track() or record() call.

Protecting sensitive text

Add the doNotCapture attribute to any element whose text should be masked. The SDK replaces captured text with ********:

<button doNotCapture>Show balance: $12,500</button>
<span doNotCapture>john.doe@private.com</span>

Typed inputs, including <input type="password">, are masked automatically. Use doNotCapture for anything else, like a button or a label showing personal data.

doNotCapture masks the text and value, on click, change and submit. It does not hide the element's tag, id, or classes.


User Tracking Control

optIn()

Activates tracking for the current user.

intempt.optIn();

optOut()

Deactivates tracking for the current user.

intempt.optOut();

isOptedIn()

Returns boolean, whether collection is permitted for the current user.

if (intempt.isOptedIn()) {
  intempt.track({ eventTitle: 'Button Click', data: { button: 'signup' } });
}

hasOptedOut()

Returns boolean, the inverse of isOptedIn().

if (intempt.hasOptedOut()) {
  // skip anything that assumes tracking is running
}

isUserOptIn()

The original name for isOptedIn(). It still works and returns the same value. isOptedIn() is the name to use in new code, and it's the name every other Intempt SDK uses.

All tracking methods (identify, group, track, record, alias, consent, productAdd, productOrdered, productView, logOut) silently do nothing when the user is opted out. The only exception is recommendation, which works regardless of opt-in status.


Whether these calls build a profile depends on the source, not the SDK. On a Users and events source they resolve identity and update the user and account. On an Events only source they build no profile: its events are kept as raw events with no user or account. You pick this when you create the source in the console. See What a source collects.

User Identification

identify(params)

Links user actions to a specific identity.

ParameterTypeRequiredDescription
userIdstringYesUnique user identifier
eventTitlestringNoCustom event name (default: "Identify")
userAttributesobjectNoUser properties (requires eventTitle if supplied)
dataobjectNoSupplementary event data
intempt.identify({
  userId: 'user123',
  eventTitle: 'User Registration',
  userAttributes: {
    email: 'user@example.com',
    name: 'John Doe',
    plan: 'premium'
  },
  data: {
    registrationSource: 'website',
    referrer: 'google'
  }
});

alias(params)

Links two distinct user identifiers together.

ParameterTypeRequiredDescription
userIdstringYesPrimary user identifier
anotherUserIdstringYesSecondary identifier to alias
intempt.alias({
  userId: 'anonymous_123',
  anotherUserId: 'authenticated_user456'
});

Group / Account

group(params)

Connects a user with a group or business account.

ParameterTypeRequiredDescription
accountIdstringYesUnique account/group identifier
eventTitlestringNoCustom event label (default: "Identify")
accountAttributesobjectNoAccount properties (requires eventTitle if supplied)
intempt.group({
  accountId: 'company_abc',
  eventTitle: 'Account Created',
  accountAttributes: {
    name: 'Acme Corp',
    plan: 'enterprise',
    employees: 500
  }
});

Event Tracking

track(params)

Records a custom event with associated data.

ParameterTypeRequiredDescription
eventTitlestringYesEvent name
dataobjectYesEvent data (must be non-empty)
intempt.track({
  eventTitle: 'Purchase Completed',
  data: {
    orderId: 'order_123',
    amount: 99.99,
    currency: 'USD',
    items: ['product1', 'product2']
  }
});

record(params)

Captures an event with optional user and account context.

ParameterTypeRequiredDescription
eventTitlestringYesEvent name
userIdstringNoUser identifier
accountIdstringNoAccount identifier
userAttributesobjectNoUser properties
accountAttributesobjectNoAccount properties
dataobjectNoSupplementary event data
intempt.record({
  eventTitle: 'Feature Used',
  userId: 'user123',
  accountId: 'account456',
  data: { feature: 'analytics_dashboard', duration: 300 },
  userAttributes: { role: 'admin' },
  accountAttributes: { plan: 'enterprise' }
});

consent(params)

Registers user consent preferences.

ParameterTypeRequiredDescription
action'accept' | 'reject'YesConsent decision
validUntilnumberYesExpiration timestamp (Unix)
emailstringNoUser email
messagestringNoConsent statement
categorystringNoConsent classification
intempt.consent({
  action: 'accept',
  validUntil: Date.now() + (365 * 24 * 60 * 60 * 1000),
  email: 'user@example.com',
  category: 'analytics'
});

Product Tracking

productAdd(params)

Logs when a product is added to the cart. Fires event title "Added to cart".

ParameterTypeRequiredDescription
productIdstringYesProduct identifier
quantitynumberNoQuantity added (default: 1)
intempt.productAdd({ productId: 'prod_123', quantity: 2 });

productOrdered(params[])

Records purchased products on checkout completion. Fires event title "Product ordered".

intempt.productOrdered([
  { productId: 'prod_123', quantity: 2 },
  { productId: 'prod_456', quantity: 1 }
]);

productView(productId)

Captures when a product page is viewed. Fires event title "Product viewed".

intempt.productView('prod_123');

On Shopify stores (with &shopify=1 in the script URL), product views and add-to-cart events are also detected automatically — no manual calls needed.


Session Management

logOut()

Clears session data and refreshes auto-tracking state. Only executes if the user is currently opted in.

intempt.logOut();

Recommendations

recommendation(params)

Fetches personalized product recommendations.

ParameterTypeRequiredDescription
idnumberYesFeed identifier
quantitynumberYesNumber of recommendations
fieldsstring[]YesFields to include in response

Returns: Promise<any> — recommendation data, or null on failure.

Unlike the other tracking methods, recommendation works even when the user is opted out.

const recommendations = await intempt.recommendation({
  id: 123,
  quantity: 10,
  fields: ['productId', 'name', 'price', 'image']
});

if (recommendations) {
  console.log('Recommended products:', recommendations);
}

DOM Events

Every tracking call fires custom DOM events you can listen to:

// Fires on every tracking method
window.addEventListener('intempt:event', (event) => {
  console.log('Intempt event:', event.detail);
});

// Method-specific events
window.addEventListener('intempt:identify', handler);
window.addEventListener('intempt:alias', handler);
window.addEventListener('intempt:group', handler);
window.addEventListener('intempt:track', handler);
window.addEventListener('intempt:record', handler);
window.addEventListener('intempt:consent', handler);
window.addEventListener('intempt:product', handler); // productAdd, productOrdered, productView
window.addEventListener('intempt:logOut', handler);

Forbidden Event Titles

The following titles are reserved and will throw an error:

auto-track · view page · leave page · change on · click on · submit on · identify · consent


Error Handling

try {
  intempt.identify({ userId: 'user123' });
} catch (error) {
  console.error('Tracking error:', error.message);
}

Common errors:

ErrorCause
"All config fields must be provided."Missing SDK config params
"Parameters for the '{method}' method are required."Called with no arguments
"'{field}' is required."Missing required field
"The '{eventTitle}' event title is forbidden"Reserved event title used

Tips & Gotchas

  • All methods take a single object — e.g. track({ eventTitle, data }). The two exceptions are productView('id') (a plain string) and productOrdered([...]) (an array).
  • Validation throws. Missing a required field (like userId on identify) or using a reserved title raises an error. Wrap calls in try/catch if a bad payload shouldn't break your page.
  • No getProfileId(). Profile, session, and page IDs are managed internally and attached to events automatically — there is no public getter to read them back.
  • Local testing. The localhost guard is active by default. Use a staging domain to see events flow through.

Type Reference

interface IdentifyParams {
  userId: string;
  eventTitle?: string;
  userAttributes?: Record<string, any>;
  data?: Record<string, any>;
}

interface GroupParams {
  accountId: string;
  eventTitle?: string;
  accountAttributes?: Record<string, any>;
}

interface TrackParams {
  eventTitle: string;
  data: Record<string, any>;
}

interface RecordParams {
  eventTitle: string;
  accountId?: string;
  userId?: string;
  accountAttributes?: Record<string, any>;
  userAttributes?: Record<string, any>;
  data?: Record<string, any>;
}

interface AliasParams {
  userId: string;
  anotherUserId: string;
}

interface ConsentParams {
  action: 'accept' | 'reject';
  validUntil: number;
  email?: string;
  message?: string;
  category?: string;
}

interface ProductParams {
  productId: string;
  quantity?: number;
}

interface RecommendationParams {
  id: number;
  quantity: number;
  fields: string[];
}

Feature flags

Read a flag by key. You never name a mode — Intempt resolves whether that key is an experiment, a personalization or a flag, so a key can change mode without your code changing.

const on = await intempt.variation('new_checkout', { userId: 'u-1' }, false);
const all = await intempt.allFlags({ userId: 'u-1' });
CallReturns
variationjust the value
allFlagsevery flag for this person, in one call

The default is required. It is what you receive on a network failure, a timeout, an unknown key or a malformed response — so an outage degrades to your existing behaviour instead of an exception.

Evaluation is remote. There is no local rule engine and no flag store to poll, so bucketing can never disagree between your code and the platform.

Typed helpers

variation returns whatever the flag holds. When you know the shape, these return it already typed and fall back to the default if the served value is the wrong type — so a misconfigured flag degrades instead of throwing.

CallReturns
boolVariationa boolean
stringVariationa string
numberVariationa number

There is no JSON helper here yet — use variation and parse the value yourself. The Node, Python, PHP and Swift SDKs do have one.

Every Intempt SDK exposes these same three calls and hits the same endpoint, optimization/choose-api — there is no separate web, mobile or backend endpoint. What the console labels server-side means the value is read by an SDK rather than authored in the visual editor; it is not a statement about which machine runs your code.

See the feature flags guide for rollout, off values and key locking.

On this page