Attributes (V3)

WARNING: This page only concerns the Batch Web SDK V3 and is deprecated since V4 is out. You should think to migrate on the latest version.

In addition of overriding the language/region or setting a custom user ID, you can assign tag collections and attributes to your users, allowing you to improve your targeting. Batch Web SDK v3 or higher is required to use this feature.

Custom attributes

IMPORTANT
- User IDs (email address, username, etc) must be managed using our custom user ID implementation.
- Region/language data must be managed using our custom region/language implementation.
- Never use an existing tagging plan. Read our guide on custom data before tagging your app.
- Newly tracked attributes and tags are hidden by default. You will need to manually display them from the dashboard settings > "Custom data" tab.

Managing attributes

Before we get started on how to implement attributes, here are some rules you should know.

Naming

Attribute names are strings. They should be made of letters, numbers or underscores ([a-z0-9_]) and can't be longer than 30 characters (e.g. has_premium).

Values

Values must be any of the following types:

  • String
    Must not be longer than 64 characters and can't be empty or nullish. For better results, you should make them upper/lowercase and trim the whitespaces.
  • Floats/Doubles (number)
  • Integer/Longs (number)
  • Boolean
  • Date, using the Javascript Date object
  • URLs, not longer than 2048 characters and following the scheme://[authority][path][?query][#fragment] format

Attribute typing

The type of your values is important: when exploiting your attributes in campaigns, the operations available on your attributes are optimized for their type. As attributes are not converted by our servers, their type must be properly defined when tracking it from the SDK.

Batch handles attribute typing in two ways:

  • Explicit typing: Provide both a value and a type. This is the recommended approach.
    Available types are STRING, BOOLEAN, FLOAT, INTEGER, DATE, URL and their constants are available in api.userAttributeTypes.
    Since the type is explicit, Batch will attempt to convert the value to the requested type (example: a INTEGER typed value passed as a string will be converted to a number).
    Always try to use the right value type rather than relying on this feature: If the value cannot be safely converted, the attribute will be ignored.
  • Autodetection: Provide a value, Batch will autodetect its type. Make sure that the type fits the represented data in the most appropriate way.

Editing the attributes

To edit user data, call editUserData(). This method takes a single argument: a callback where Batch will give you an instance of the user data editor. Your changes should then be performed in this callback.

Once the callback finishes, Batch automatically saves the changes and syncs them with the server: this is called a transaction.

Note: The editor object is only valid in the callback function scope. Using it outside of the callback will throw an exception.

batchSDK(api => {
  api.editUserData(editor => {
    editor.setAttribute("age", 26); // Set an attribute. The "integer" type is autodetected.
    editor.setAttribute("signup_date", {
      type: api.userAttributeTypes.DATE,
      value: new Date('2022-02-08T15:00:00Z'),
    }); // Explicit typing
    editor.removeAttribute("age"); // Remove an attribute
    editor.clearAttributes(); // Remove all attributes
  });
});
You might be tempted to write helpers or loops that open and save many transactions in a row, with each transaction only doing one operation.
Doing so prevents Batch from optimizing disk usage and network roundtrips, which impact your user's data plan and battery life.
Please try to batch as many operations as you can in a single transaction.

Trying to edit the user data before calling batchSDK('setup', ...) is not supported and will throw an exception.
An attribute that doesn't satisfy name or value requirements will be ignored but the transaction will not fail.

Please test your implementation using our debug tool before going live.

Managing tag collections

You can attach multiple tags to different collections. Collections names can't be longer than 30 characters (e.g. favorite_categories).

Tags have some limitations:

  • They are strings.
  • They will automatically be lowercased.
  • Their size can't be greater than 64 characters and they can't be empty or nullish.

Collection names have the same limitations as attribute names.

Example:

batchSDK(api => {
  api.editUserData(editor => {
    editor.addTag("interests", "sports"); // Add the "sports" tag to the "interests" collection
    editor.addTag("interests", "weather");
    editor.removeTag("interests", "sports"); // Remove a tag
    editor.clearTagCollection("interests"); // Removes all tags from that collection
    editor.clearTags(); // Remove all tag collections and their tags
  });
});

A tag that doesn't satisfy tag collection name or value requirements will be ignored but the transaction will not fail.

Limits

A single installation can’t hold more than:

  • 50 attributes
  • 15 tag collections
    • 50 tags per tag collection

If after applying the transaction the sum of all attributes or tags exceeds those limits, an error will be logged and the transaction will be rolled back: none of your changes will be saved.

Reading attributes and tag collections

Attributes and tag collections can be read back from the SDK:

Reading attributes

batchSDK(api => {
  // Attributes are retrieved in the form of an object
  // Values are encapsulated in an instance of BatchSDK.IUserAttribute
  // Attributes is of type { [key: string]: IUserAttribute }
  api.getUserAttributes()
    .then(attributes => {
      // age if of type BatchUserAttribute
      const age = attributes["age"];
      // BatchUserAttribute holds a reference to the value of the attribute
      const rawValue = age.getValue(); // Raw value is not typed

      // The type of the value is specified using the BatchUserAttributeType enumeration
      console.log(age.getType() === api.userAttributeTypes.INTEGER); // Prints true

      // To obtain a typed result you can use one of the three helper methods, which returns undefined if there is a type mismatch
      age.getNumberValue(); // Will return "26" here
      age.getBooleanValue();   // Will return undefined here
      age.getDateValue(); // Will return undefined here
      age.getStringValue(); // Will return undefined here
    })
    .catch(console.error);
});

Reading tag collections

batchSDK(api => {
  api.getUserTagCollections()
    .then(tagCollections => {
      // Tags are also retrieved in the form of an object
      // Keys are names of collections, values are lists of tags
      // TagCollections if of type  [key: string]: string[] }
    })
    .catch(console.error);
}

Note: Keep in mind that since tag collections and their tags have their casing normalized, they might be slightly different when read back.

Installation eligibility

Attributes and tags are sent to Batch's servers once a user has successfully subscribed to notifications at least once.
If a user isn’t subscribed to push notifications, the attributes and tags are still saved locally and can be read back as expected.

Debugging

Event tracking errors are hidden by default. It can be useful to enable them in development/testing, as they will show if tracked events have been discarded due to validation errors.

To do so, open your developer tools and paste the following in the console:

window.localStorage.setItem("com.batch.private.logger.level", "4");
window.localStorage.setItem("com.batch.private.logger.modules.enabled", '["*"]');