> For the complete documentation index, see [llms.txt](https://fredhopper.gitbook.io/product-discovery/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://fredhopper.gitbook.io/product-discovery/tracking-and-sending-events/identities/working-with-identities.md).

# Working with Identities

Track user identities with session IDs, e-commerce IDs, segments, and traits using SDK, GTM, or REST API, ensuring accurate tracking, personalization, and GDPR compliance.

To send an event, you have to provide at least one identifier: the **session ID**. When a visitor arrives at your website or app, they may initially be anonymous until they log in. During their visit, you can generate an anonymous session ID to track their journey. Store the session ID locally (in a cookie or local storage) and include it with every event using the `user.identities.sessionId` field.

In the sections below, we go into detail about how to implement identities with each [implementation method](/product-discovery/tracking-and-sending-events/implementation-guide.md).

## SDK

### Session ID

If you are using the Javascript SDK, a random **session ID** is created for the visitor and automatically stored in local storage as `attraqtsessionid`. This **session ID** is then attached to any event sent through the library.

{% hint style="info" %}
If you have a different **session ID** that's generated elsewhere in your system and want to use it, add it through the `addUserIdentity` method:

```javascript
xo.activity.addUserIdentity('sessionId', 'session-id');
```

{% endhint %}

{% hint style="warning" %}
The SDK **only** stores the **session ID** in local storage. You will need to re-add any additional identities each time a page is loaded.
{% endhint %}

### Logins

Once the shopper logs in, you know exactly who they are through the ID you have for them in your system, for example an **e-commerce ID**. The **e-commerce ID** can then be added to subsequent events along with the already existing **session ID**.

#### Adding an identity

Use `addUserIdentity` to add a different identity, e.g. the **e-commerce ID**:

```javascript
xo.activity.addUserIdentity('ecommerceId', 'e-commerce-id');
```

#### Adding multiple identities

Use the `setUserIdentities` method to add multiple identities at once or to overwrite any pre-existing identities added with `addUserIdentity`:

```javascript
const identities = { 
    ecommerceId: 'e-commerce-id', 
    sessionId: 'session-id' 
};

xo.activity.setUserIdentities(identities);
```

### Example: Handling user identities

The following sequence demonstrates how the SDK handles user identities and ensure accurate tracking throughout a user's journey on your platform:

1. **User arrives on your platform**: The SDK assigns a default **session ID** and stores it in local storage.
2. **User performs actions**: The SDK attaches the **session ID** to any activity event you send out through the SDK.
3. **User logs in**: You retrieve the user's **e-commerce ID** from the login and attach it to all subsequent events.
4. **User performs more actions**: The SDK attaches both the newly added **e-commerce ID** as well as the already existing **session ID** to any activity event you send out. On the first activity sent this way, we attribute the **session ID** to the **e-commerce ID**, so all previous actions are now assigned to the same user.

### Segments and Traits (XO specific)

{% hint style="info" %}
This section is relevant for **XO** customers only.
{% endhint %}

Apart from **identities**, the SDK can also handle **segments** and **traits**. Segments constitute labels to qualify groups of users sharing common traits or behaviors, such as "Frequent buyer" or "Prospect". Traits constitute various qualifying values related to the user in question, including profile, and preference data, age, gender, likes, etc.

#### Setting a user segment

Use the `addUserSegment` method to set a user segment. For example:

```javascript
xo.activity.addUserSegment('new');
```

#### Setting multiple user segments

Use the `setUserSegments` method to set multiple segments at once and overwrite any pre-existing ones set by `addUserSegment`. For example:

```javascript
const segments = ['new', 'prospect'];

xo.activity.setUserSegments(segments);
```

#### Adding a trait

Use the `addUserTrait` method to add a trait for the user. For example:

```javascript
xo.activity.addUserTrait('age', '45');
```

#### Adding multiple traits

Use the `setUserTraits` method to set multiple traits for the user at once and overwrite any pre-existing ones set by `addUserTrait`. For example:

```javascript
var traits = {
    age: 45,
    buyer: true
};

xo.activity.setUserTraits(traits);
```

{% hint style="danger" %}
Traits are information you know about your users and that you want to use in our platform. You **must** **only** send information relevant to the platform usage and avoid sending personal information.
{% endhint %}

### Logouts

If a user logs out, you shouldn't continue to attribute any future events to the same user until they log in again. To clear all user information (and generate a new **session id**) use the `clearUser` method:

```javascript
xo.activity.clearUser();
```

### Opting Out

In order to be compliant with GDPR policies, you must allow your users to opt-out of saving cookies and having their information tracked. You should not be tracking any information on such users, and should refrain from sending any events.

When using the SDK to send activity events and the user decides to opt-out, call the following method:

```javascript
xo.activity.optOut();
```

If the user decides to opt-in again, use the following method:

```javascript
xo.activity.optIn();
```

### Handling the user object yourself

If you would like to set the complete user object, you can override any pre-existing configuration through the `setUser` method:

```javascript
const user = {
    'identities': {
        'sessionId': 'session-id',
    },
    'segments': ['new']
}

attraqt.activity.setUser(user);
```

You can also attach the user object as part of the activity object every time you send an activity, for example:

```javascript
const activity = {
  "action": "view",
  "target": {
    "product": "123"
  },
  "user": {
    "identities": {
      "sessionId": "f49c75a2-6994-41e2-875d-97ec4d19254b",
      "ecommerceId":"0ca79556-2fee-11eb-adc1-0242ac120002"
    },
    "segments": ["new", "prospect"],
    "traits": {
      "age": 45,
      "buyer": true
    }
  }
};

xo.activity.send(activity);
```

## GTM

If you are using our [GTM templates](/product-discovery/tracking-and-sending-events/implementation-guide/google-tag-manager.md), identities are added as key-value pairs in the **Identities** section.

To add **segments** or **traits**, include them in the **User information** section.

## REST API

If you are using the **REST API** to send events, you can attach the user object as part of the activity object every time you send an activity. For example:

```
curl "https://collect-eu.attraqt.io/30cbb5fc-375f-4cf2-8efd-ed86d909718e"
      -X POST 
      -H "Content-Type: application/json"
      -d '{
            "action": "view",
            "target": {
              "product": "123"
            },
            "user": {
              "identities": {
                "sessionId": "session-id",
                "ecommerceId":"e-commerce-id"
              },
              "segments": ["new", "prospect"],
              "traits": {
                "age": 45,
                "buyer": true
              }
            }
          }'
```
