Attributes

This page is about the latest SDK version, if your app still running on sdk v3 you could be interested in our legacy documentation.

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

Since v4 of the Batch Web SDK, your data will also be attached to your profiles if your application belongs to a project.

Custom attributes

IMPORTANT
- User IDs (Username, etc) must be managed using our custom user ID implementation.
- Email address must be managed using our email subscription 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 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. For better results, you should make them upper/lowercase and trim the whitespaces.
  • Float/Double (number)
  • Integer/Long (number)
  • Boolean
  • Date, using the Javascript Date object
  • URL, using the Javascript URL object, not longer than 2048 characters and following the scheme://[authority][path][?query][#fragment] format
  • Array<string>, not longer than 25 items, only values of type String and must respect the string attribute limitations. Values will automatically be lowercased.

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, ARRAY and their constants are available from 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 profile data, please use:

api.profile().edit() // or api.editUserData() if running on SDK v3

This method takes a single argument: a callback where Batch will give you an instance of profile 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 the callback will throw an exception.

Example:

  • Javascript (ES8)
  • Javascript
batchSDK(async api => {
    const profile = await api.profile();
    await profile.edit(editor => {
        // Setting an autodetected "integer" attribute.
        editor.setAttribute("age", 26); 
        
        // Setting an explicit "Date" attribute.
        editor.setAttribute("signup_date", {
          type: api.userAttributeTypes.DATE,
          value: new Date('2022-02-08T15:00:00Z'),
        }); 
        
        // Removing an attribute
        editor.removeAttribute("age");
        // or
        editor.setAttribute("age", null)
        
        // Adding values to an Array attribute
        editor.addToArray("interests", ["sports", "weather"])
        
        // Removing values from an Array attribute
        editor.removeFromArray("interests", ["sports"])  
    })
});

Warning: The edit method return a Promise, so if you are doing some work after (like trackEvent or identify), don't forget to use await or then in order to guarantee the execution order.

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 profile 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 and profile view before going live.

Limits

A single transaction can’t hold more than:

  • 50 attributes
  • 15 array attributes
  • 25 items per array attribute

If after applying the transaction the sum of all attributes 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:

WARNING:
  • Since Batch SDK v4, updating the user's data also update the profile's data to be accessible from your project scope. This mean the following APIs only read local data related to your installation and NOT to your profile.
  • You may also have noticed that APIs to set Tags or Tag Collections have been removed from the SDK v4 and replaced by array attributes. These methods are backward-compatible and array attributes are converted into tag collections to not break your implementation.

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.

Clearing installation data

Installation data can be cleared as following:

  • Javascript (ES8)
  • Javascript
  batchSDK(async api => {
    await api.clearInstallationData();
  });

Note: This method will clear the installation data on the App scope and will NOT affect the profile related data.

Installation eligibility

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

Profile eligibility

Attributes are sent to Batch's servers but will not be processed until the profile be identified or the user has successfully subscribed to notifications at least once.

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", '["*"]');