TwinrDocs
Native features and APIs / Track Events and Users

Track Events and Users

Tell the app who is signed in, and record the events, purchases and pages that matter to your business.

The app already counts sessions and page views on its own. These JavaScript functions let your website add what only it knows: who is signed in, what they did, what they bought and what kind of customer they are.

Function What it does
twinr_identify Tells the app who is signed in
twinr_set_traits Saves details about that person, such as their plan
twinr_track Records an event, such as add to cart, or an order
twinr_page Records a page view, for sites that change pages without reloading
twinr_logout Tells the app the person signed out
twinr_opt_out / twinr_opt_in Stops or restarts tracking on this device
twinr_debug Shows each call and its result in the browser console

twinr_identify, twinr_logout, twinr_set_traits, twinr_page, twinr_opt_out and twinr_opt_in work on every active plan.

twinr_track with your own event names needs the Premium plan or your free trial. The revenue events purchase, order_completed and product_purchased work on every active plan.

A call your plan doesn't allow answers NOT_ENABLED.

Test on a new build of your app. The Preview App can run an older version, where these functions are missing and the guard below answers NOT_IN_APP.

Add the guard first

Your website also opens in ordinary browsers, where these functions don't exist. Add this once, before any other code that calls them, for example in your page's <head>:

JAVASCRIPT
(function () {
  var names = [
    'twinr_identify', 'twinr_logout', 'twinr_set_traits', 'twinr_track',
    'twinr_page', 'twinr_opt_out', 'twinr_opt_in', 'twinr_debug'
  ];
  names.forEach(function (name) {
    window[name] = window[name] || function () {
      return Promise.resolve({ ok: false, code: 'NOT_IN_APP' });
    };
  });
})();

Inside the app, the real functions are already there and the guard leaves them alone. Everywhere else, each call quietly answers NOT_IN_APP instead of breaking your page.

Every function returns a Promise. It never throws an error; it resolves to one of these:

JAVASCRIPT
{ ok: true }
{ ok: false, code: 'INVALID_NAME', message: 'event name must match ...' }

ok: true means the app accepted the call. Events and page views are sent in the background, and are kept on the phone until it is back online.

The functions work in your page itself, not inside iframes.

Tell the app who is signed in

Call twinr_identify right after your own login has succeeded:

JAVASCRIPT
twinr_identify({
  user_id: '[email protected]',   // required
  email: '[email protected]',     // optional
  name: 'Jane Doe',              // optional
  traits: { plan: 'gold' }       // optional, see below
});

user_id is required and must be text. If your id is a number, convert it: String(1234).

Use the same id as automatic login detection

If you set up a login script, or your site runs on Shopify, the app already notices sign-ins and sign-outs by itself. That keeps working. Pass the same user_id it uses, so both name the same person:

Your site Pass as user_id
Most sites The username the person signs in with. If it is an email address, in lowercase.
Shopify The Shopify customer id, as text: String(customerId)

Once you call twinr_identify, the app won't switch to a different person from automatic detection until the next logout. So a mismatch can't make one device flip between two people, but it can split one person into two.

Save details about a person

Traits describe the person who is signed in: their plan, their loyalty tier, whether they want the newsletter.

JAVASCRIPT
twinr_set_traits({
  plan: 'gold',
  orders_count: 3,
  newsletter: true,
  old_coupon: null   // null removes a trait
});

You can also send traits with twinr_identify, as shown above.

  • Each trait keeps the type of the first value it was given. If orders_count started as a number, keep sending numbers; a value of another type is ignored.
  • An app can have up to 40 different trait names; new names after that are ignored. Pick a small set and reuse it.

Record an event

JAVASCRIPT
twinr_track('add_to_cart', {
  product_id: 'SKU-123',
  price: 19.99,
  in_stock: true
});

The second argument, the event's properties, is optional: twinr_track('newsletter_signup').

Your own event names need the Premium plan or your free trial. On other plans, the call answers NOT_ENABLED with the message Custom events need the Premium plan.

Record an order

When an order completes, send order_completed once, and product_purchased once for each product in it:

JAVASCRIPT
twinr_track('order_completed', {
  order_id: 'A-1001',
  value: 39.98,          // the order total, a number
  currency: 'USD'        // three capital letters
});

twinr_track('product_purchased', {
  order_id: 'A-1001',
  product_id: 'SKU-123',
  name: 'Blue shirt',
  price: 19.99,          // the price of one item
  quantity: 2,
  currency: 'USD'
});

These two names are reserved: App Analytics uses them for revenue, orders and top products. They work on every active plan. See Track Custom Events for every property.

If your site already sends purchase, switch to order_completed. App Analytics doesn't count purchase as revenue.

Record pages yourself

The app records a page view each time a page loads or the address changes. Single-page sites that swap content without changing the address can record pages themselves:

JAVASCRIPT
twinr_page({ path: '/products/blue-shirt', title: 'Blue shirt' });

path can be a path on your site or a full address. title is optional.

Once a page calls twinr_page, the app stops tracking pages automatically in that tab. Call it on every page, or not at all. Calling it on some pages only means the other pages are no longer counted.

When someone signs out

Call this when your site signs the person out:

JAVASCRIPT
twinr_logout();

Events after this belong to an anonymous visitor until the next sign-in.

Let people opt out

If your site offers a tracking choice, connect it to these:

JAVASCRIPT
twinr_opt_out();   // stop tracking on this device
twinr_opt_in();    // start again

Opting out stops page views, events and traits from this device, and deletes any that were waiting to be sent. The app remembers the choice until twinr_opt_in is called. While opted out, twinr_track, twinr_page and twinr_set_traits answer OPTED_OUT.

The app still knows who is signed in, so notifications and inbox messages keep reaching the right person, and app sessions are still counted.

Check your setup

JAVASCRIPT
twinr_debug(true);

Until the app is closed, every call and its result is written to the browser console, along with any event or page view Twinr's servers turned away and why. Call twinr_debug(false) to stop.

To see the console on Android, connect the phone to a computer and open chrome://inspect in Chrome. iPhone builds don't allow this, so you can also log the result yourself:

JAVASCRIPT
twinr_track('add_to_cart', { product_id: 'SKU-123' }).then(function (result) {
  console.log(result);
});

Limits

What Rule
Event name Starts with a lowercase letter, then lowercase letters, digits or _. Up to 64 characters.
Properties per event Up to 25
Property value Text, a number, or true/false. No objects, lists or null.
Text value Up to 255 characters
Trait name Letters, digits, _, . or -, not starting with . or -. Up to 64 characters.
Trait value Text up to 255 characters, a number, or true/false. null removes the trait.
Orders value and price are numbers. currency is three capital letters, like USD or EUR.
Page title Longer titles are cut to 255 characters.

Naming events

  • Use lowercase words joined by underscores: add_to_cart, not AddToCart or add-to-cart.
  • Name the action, not the button: checkout_started still makes sense after a redesign.
  • Keep changing details out of the name. Send twinr_track('view_product', { product_id: 'SKU-123' }), not view_product_sku_123.
  • Pick names once and reuse them. Two spellings are two separate events.
  • Never put personal details, such as an email address, in an event name.

Results

Code What it means What to do
NOT_IN_APP Answered by the guard: the page is in a browser, or in an app built before SDK 19.30.0. Nothing in a browser. In the app, request a new build.
NOT_ENABLED The app's plan doesn't allow this call. For twinr_track with your own event name, message is Custom events need the Premium plan. Move to Premium for your own event names. Other calls need an active plan.
OPTED_OUT Tracking is turned off on this device. Nothing. Respect the person's choice.
INVALID_ARGUMENT Something is missing or the wrong type: no user_id, a property set to null, a price sent as text. Read message and fix the call.
INVALID_NAME The event name or a trait name breaks the naming rules. See Limits.
TOO_MANY_PROPERTIES More than 25 properties. Send fewer.
VALUE_TOO_LONG A text value is over 255 characters. Shorten it.
NESTED_PROPERTY A value is an object or a list. Send each detail as its own property.
NOT_REGISTERED The app hasn't finished setting up on this device, usually in the first moments after install or while offline. Try again later, for example on the next page.
REQUEST_FAILED Twinr couldn't be reached, or had a problem. Try again later.
invalid_request Twinr's servers refused a value. Read message; it names the field.
too_large The call carried too much data. Send fewer traits at once.
invalid_key Twinr didn't recognise the app. Contact support.
device_not_found Twinr didn't recognise this device. Try again later; the app sets itself up again.

What the app trusts

  • The app key tells Twinr which app is talking, not who is using it. It is built into your app, so it proves nothing about the person.
  • twinr_identify believes your page. Whatever user_id your page passes becomes the signed-in person. Call it only after your own login has succeeded, with the id your login returned. Never take it from a form field, the address bar or anything a visitor can type.
  • Never send passwords, card numbers or other secrets in any field, property or trait.

Twinr events and custom events

Custom events are configured in your Twinr dashboard, and also go to your Firebase project when Firebase Analytics is set up. twinr_track events need no setup, take any name from your code, are tied to the person who is signed in, and are recorded in Twinr.

On apps built with SDK 19.30.0 or later, custom events are also recorded in Twinr automatically: webpage element clicks and twinr_firebase_analytics_event calls set up in Custom Events, hamburger menu items and navigation bar buttons. The Twinr name is the event name in lowercase.

So if an action already has a custom event, don't also send it with twinr_track, or Twinr counts it twice.

Which app versions support this

Built before SDK 19.30.0 Built with SDK 19.30.0 or later
Page views and sessions Yes Yes
Automatic login detection Yes Yes, and it also notices form submits
Custom events In Firebase only In Firebase and in Twinr
Everything else on this page No, the guard answers NOT_IN_APP Yes

Paste this into your AI builder

If an AI tool builds your site, paste this into it and fill in the two blanks:

Code
Add Twinr app tracking to this site.

1. In the <head> of every page, before other scripts, add this guard so the
   functions are safe in normal browsers:

   (function () {
     var names = ['twinr_identify', 'twinr_logout', 'twinr_set_traits',
       'twinr_track', 'twinr_page', 'twinr_opt_out', 'twinr_opt_in', 'twinr_debug'];
     names.forEach(function (name) {
       window[name] = window[name] || function () {
         return Promise.resolve({ ok: false, code: 'NOT_IN_APP' });
       };
     });
   })();

2. Right after a login succeeds (never before), call
   twinr_identify({ user_id: <the username the person logged in with, lowercased
   if it is an email address>, email: <email if known>, name: <name if known> }).
   user_id must be a string. Never send a password.

3. When the user logs out, call twinr_logout().

4. Record these actions with twinr_track(name, properties): [LIST YOUR ACTIONS].
   Event names: lowercase letters, digits and underscores, starting with a letter,
   up to 64 characters. At most 25 properties. Property values are strings (max 255
   characters), numbers or booleans only: no objects, arrays or null.

5. When an order completes, call twinr_track('order_completed', { order_id: <id>,
   value: <total as a number>, currency: <3-letter uppercase code like 'USD'> }),
   then for each product in it call twinr_track('product_purchased', {
   order_id: <same id>, product_id: <id>, name: <product name>, price: <price of
   one item as a number>, quantity: <whole number>, currency: <same code> }).

6. [Only if the site is a single-page app that changes content without changing
   the URL:] call twinr_page({ path: <path>, title: <title> }) on every page change,
   including the first page. If you call it on some pages, call it on all of them.

All of these functions return a Promise of { ok: true } or
{ ok: false, code, message }. They never throw. Do not await them in a way that
blocks the page.

Location data

Twinr estimates a device's approximate location from its internet address.

This product includes GeoLite2 data created by MaxMind, available from https://www.maxmind.com.