# Analytics Kotlin Mixpanel Plugin

[Mixpanel](https://mixpanel.com/?utm_source=segmentio\&utm_medium=docs\&utm_campaign=partners) is an event-tracking and segmentation platform for your web and mobile apps. By analyzing the actions your users perform, you can gain a better understanding to drive retention, engagement, and conversion. The client-side Mixpanel Destination code is open-source.

Segment's Mixpanel destination plugin code is open source and [available on GitHub](https://github.com/segment-integrations/analytics-kotlin-mixpanel).

## Getting started

1. From the Segment workspace **Destinations** page, click **Add Destination**.
2. Search for *Mixpanel* in the Destinations Catalog and confirm the source to connect to.
3. Copy your Mixpanel "API Secret" and "Token", and paste them into the Connection Settings in Segment.
4. Enable the destination to start sending your data to Mixpanel.

## Adding the dependency

To install the Segment-Mixpanel integration, add this line to your gradle file:

```text
implementation 'com.segment.analytics.kotlin.destinations:mixpanel:<latest_version>'
```

Or the following for Kotlin DSL:

```text
implementation('com.segment.analytics.kotlin.destinations:mixpanel:<latest_version>')
```

## Using the plugin in your app

Open the file where you set up and configure the Analytics-Kotlin library. Add this plugin to the list of imports.

```text
import com.segment.analytics.kotlin.destinations.mixpanel.MixpanelDestination
```

Under your Analytics-Kotlin library setup, call `analytics.add(plugin = ...)` to add an instance of the plugin to the Analytics timeline.

```text
    analytics = Analytics("<YOUR WRITE KEY>", applicationContext) {
        this.flushAt = 3
        this.trackApplicationLifecycleEvents = true
    }
    analytics.add(plugin = MixpanelDestination(applicationContext))
```

Your events will now begin to flow to Mixpanel in device-mode.

## Identify

If you're not familiar with the Segment Specs, take a look to understand what the [Identify method](/docs/segment/connections/spec/identify/) does. An example call would look like:

```java
analytics.identify("user-123", buildJsonObject {
    put("username", "MisterWhiskers")
    put("email", "hello@test.com")
    put("plan", "premium")
});
```

The first thing you'll want to do is to identify your users so Mixpanel knows who they are. You'll use the Identify method to accomplish this which takes the unique `userId` of a user and any `traits` you know about them.

> \[!NOTE]
>
> Mixpanel used to require that you call `alias` in all libraries to connect anonymous visitors to identified users. However, since the release of Mixpanel's [Identity Merge feature](https://help.mixpanel.com/hc/en-us/articles/360039133851#enable-id-merge) this is no longer necessary.
>
> To enable ID Merge, go to your Mixpanel Settings Dashboard, navigate to **Project Settings > Identity Merge** and enable the setting from that screen. If you are *not* using this setting, use the instructions below.

As soon as you have a `userId` for a visitor that was previously anonymous you'll need to [Alias](/docs/segment/connections/spec/alias/) their old anonymous `id` to the new `userId`. In Mixpanel only *one* anonymous user history can be merged to *one* identified user. For that reaso, only call Alias once, right after a user registered, but before the first Identify call.

When you call the Identify method from the client in either a browser using Analytics.js or one a mobile SDKs, several things occur: Segment recognizes and translates the [special traits](/docs/segment/connections/spec/identify/#traits) so that they fit the expectations of Mixpanel's API. The table below shows the mappings. Pass the `created` key and Segment transforms it to the `$created` key before sending to Mixpanel.

| `created`   | `$created`    |
| ----------- | ------------- |
| `email`     | `$email`      |
| `firstName` | `$first_name` |
| `lastName`  | `$last_name`  |
| `name`      | `$name`       |
| `username`  | `$username`   |
| `phone`     | `$phone`      |

### People

Segment doesn't send data to Mixpanel People by default. To enable Mixpanel People, change the "Use Mixpanel People" setting in the Mixpanel Destination settings in Segment.

To add people properties in Mixpanel before you know the user's unique database `userId`, you can identify `traits` without the `userId`.

## Group

Group calls are sent to Mixpanel if:

1. The Group Identifier Traits setting has one or more traits saved in the destination settings for Mixpanel.

   ![The Mixpanel Traits and Properties list showing the "Group Identifier Traits" field where one or more traits (like company\_id) can be defined for grouping users.](https://docs-resources.prod.twilio.com/b12a35e6e6e5fbc726551ae94c033e3469ad508eff69ea99540ecdd0423931fc.png)
2. You have created a group key of the same name in your Mixpanel [project settings](https://help.mixpanel.com/hc/en-us/articles/360025333632-Group-Analytics#implementation).
3. A Group trait with the same name as one of the configured Group Identifier Traits is sent with the group call.

```swift
analytics.group("user-123", buildJsonObject {
    put("username", "MisterWhiskers")
    put("email", "hello@test.com")
    put("plan", "premium")
});
```

Mixpanel supports multiple definitions of groups. For more information see [Mixpanel's Group Analytics documentation](https://help.mixpanel.com/hc/en-us/articles/360025333632-Group-Analytics).

If the Group call doesn't have a group trait that matches the Group Identifier Traits setting, then the event will be ignored.

### Register super properties

By default, each trait (that is, properties in an `identify` call) is registered as a super property. This doesn't require passing a `userId` in the `identify` call. You can pass a `traits` object by itself and it will still register the traits as super properties.

Disable **Set All Traits as Super Properties or People Properties By Default** to disable the default behavior and register super properties explicitly. For more information, see [Explicitly set People Properties and Super Properties](#explicitly-set-people-properties-and-super-properties).

> \[!NOTE]
>
> Super properties require a device mode connection.

#### Set people properties

If you've enabled Mixpanel People in your Segment settings, Segment calls Mixpanel's `people.set` with the same `traits` object. There's no need for an additional API call to populate Mixpanel People.

Disable **Set All Traits as Super Properties or People Properties By Default** to disable the default behavior and register super properties explicitly. Segment automatically includes any trait on an identify that matches one of Mixpanel's special properties, which you can see in the table above. For more information, see [Explicitly set People Properties and Super Properties](#explicitly-set-people-properties-and-super-properties).

## Track

If you're not familiar with the Segment Specs, take a look to understand what the [Track method](/docs/segment/connections/spec/track/) does. An example call would look like:

```java
analytics.track("View Product", buildJsonObject {
    put("productId", 123)
    put("productName" "Striped trousers")
});
```

Because Mixpanel is an event tracking analytics tool, you'll want to [Track](/docs/segment/connections/spec/track/) your user's actions. The more useful events you [Track](/docs/segment/connections/spec/track/), the better Mixpanel becomes.

You should use the [Track](/docs/segment/connections/spec/track/) method to accomplish this. The Segment [Track](/docs/segment/connections/spec/track/) method maps events and event properties directly to Mixpanel events and event properties.

### Track charge

If Mixpanel People is enabled in your Segment settings and you include an event property called `revenue`, Segment tracks a charge to the current user.

### Reserved properties

There are two strings to avoid when naming event properties that will be sent to Mixpanel: `length` and `bucket`. `length` is interpreted as the JavaScript `.length` method, which causes the `mixpanel.track` call to fail silently. `bucket` is a reserved property that was used in the early days of Mixpanel. If you include a property called `bucket` in your events, it will not show up in the UI. However, it will not cause the `mixpanel.track` call to fail.

### Explicitly set people properties and super properties

Previously, Segment set all traits and properties as both Super Properties and People Properties (If you had Mixpanel People enabled). Now Mixpanel allows you to segment your reports by both People Properties and Super Properties. To give you better precision and control over what property or trait gets set as a Super Property or People Property, you can disable **Set All Traits as Super Properties or People Properties By Default** and pass in the properties or traits that you want to send to Mixpanel as People or Super Properties as shown below. Segment passes through all of Mixpanel's special traits as People Properties so you only need to add the ones that aren't on [this list](#group).

![MIxpanel Traits and Properties list with Properties to increment in People option highlighted.](https://docs-resources.prod.twilio.com/ecb3f32ddc96c4da49d230c20365d8129716a407f2a7a72f64a2b2da31c4340d.png)

### Incrementing events

You don't need to add extra code to increment event counts for Mixpanel people, as long as they are "known users". Supply the events that should be incremented.

![The Mixpanel Traits and Properties list with Properties to increment in People option highlighted.](https://docs-resources.prod.twilio.com/4488b896b709feb3f85f38c0a830b03e2f0f9cf5ef4c465c44815937ced7e38f.png)

You can find this in the **Advanced Options** of your Mixpanel settings on your Segment Destinations page.

For each event name listed, Segment calls Mixpanel `increment`, and set a user trait of `Last + {{ event.name }}`.

For example, if you add **Logged In** to the list of increment events, Segment increments a user trait called **Logged In** and set a trait called **Last Logged In** with the current date and time.

If you'd like to add an increment for viewing a specific page or screen, ensure you have the setting "Track Named Pages" selected and use the dynamically generated event name under "Events to Increment in People." For example, `.page('Signup')` would translate to "*Viewed* Signup *Page*" and `.screen('Listing')` would translate to "*Viewed* Listing *Screen*".

Remember, Segment sends one event per `page` call.

> \[!NOTE]
>
> Increment works for "known users", so if your track call is being made server-side, you need to pass a `userId`. If your track call is being made client-side, you need to identify the user first.

### Incrementing properties

To increment at the property level, tell Segment which properties you want to increment using the **Properties to increment** setting and Segment calls Mixpanel's `increment` for you when you attach a number to the property (for example, `'items purchased': 5`)

### Screen

When you use the Mixpanel destination in Device-mode, Segment sends Screen events to Mixpanel as follows:

* If you select "Track all Pages to Mixpanel", all Screen calls regardless of how you have customized it will send a `Loaded A Screen`. Even if you have the other options enabled, Segment sends this call to prevent double counting your pageviews.
* If you select "Track Categorized Pages to Mixpanel", Segment sends a `Viewed [category] Screen` event.
* If you select "Track Named Pages to Mixpanel", Segment sends a `Viewed [name] Screen` event.

In short, Segment sends one event to Mixpanel per Screen call.

### When will I see data from my mobile app?

If you already have an app deployed with the Segment library, and you enabled Mixpanel mobile, it can take up to an hour for all your mobile users to refresh their Segment settings cache, and learn about the new service that you want to send to.

After the settings cache refreshes, the library starts to send data to Mixpanel.

Also worth noting, Mixpanel's SDK only submits requests to the Mixpanel servers when the app is backgrounded. That means you may see events in your Segment debugger while testing, but those requests won't actually be forwarded to Mixpanel until the app gets sent to the background.

If you're testing in Xcode remember you must first background the app, then the events will show up in Mixpanel. If you terminate the session without backgrounding those events will be lost.

### I'm seeing events come into Mixpanel but not people.

1. You'll need to make sure you're using [`identify`](/docs/segment/connections/spec/identify/). A Mixpanel track doesn't create users in Mixpanel People.
2. Make sure to turn on the "People" setting so that all of your [`identify`](/docs/segment/connections/spec/identify/) calls will be sent to Mixpanel's People feature.
3. Make sure you disable the default filter in the Mixpanel People Explore tab.

### Push notifications

Push notifications are only available for projects bundling the Segment-Mixpanel SDK.

> \[!NOTE]
>
> Set up your push notification handlers by calling into native Mixpanel methods. You can read more about how to approach this in [Android](/docs/segment/connections/sources/catalog/libraries/mobile/android/android-faqs/#how-can-i-use-a-destination-specific-feature).
