How to Integrate Mixpanel with NestJS
Tags: nestjs, mixpanel, node
Published: 2024-02-02 15:47:37

In NestJs application you can integrate Mixpanel with these simple steps:

Install the Mixpanel library:

```
yarn add  mixpanel
```
 

Create a service for Mixpanel by running the following command. The service will host all Mixpanel features like init, track, people etc.

```
nest generate service mixpanel
```

Add the following code to the `mixPanel.service` that was just created.  You can setup the ConfigService or just pass your Mixpanel project token to the init() method as shown below.

```
import * as Mixpanel from 'mixpanel';
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';

@Injectable()
export class MixpanelService {
  private mixpanel: any;

  constructor(private configService: ConfigService) {
    this.mixpanel = Mixpanel.init(
       "mixPanel Project Token", //this.configService.get<string>('mixPanelToken'),
      {
        debug: true,
        // protocol: 'http',
      },
    );
  }

  public track(eventName: string, action: any = {}): void {
    this.mixpanel.track(eventName, action);
  }
}
```
To track an event in a module, add the mixPanel service to the module constructor:

```
  constructor(
    ....
    private readonly mixpanelService: MixpanelService,
  ) {}
```

example track:

```
    this.mixpanelService.track('Sign Up', {
        $first_name: 'John,
        $last_name: 'Doe,
        $created: new Date().toISOString(),
        type: 'patient',
        distinct_id: 'userId',
        //ip: ip.address(),
      });
```
That is all when integrating Mixpanel with your NestJS app using a dedicated Mixpanel service. You can find more information on Mixpanel's documentation.

**FULL CODE**

app.module

```
import { Module } from '@nestjs/common';
import { AppService } from './app.service';
import { ConfigModule } from '@nestjs/config';
import { AppController } from './app.controller';
import { MixpanelService } from './mixpanel/mixpanel.service';

@Module({
  imports: [
    ConfigModule.forRoot({
      envFilePath: [
        '.env.production',
        '.env.development',
        '.env',
      ],
      // load: [configuration],  //for env variables
      isGlobal: true,
    }),
  ],
  controllers: [AppController],
  providers: [AppService, MixpanelService],
})
export class AppModule {}

```
mixpanel.service

```
import * as Mixpanel from 'mixpanel';
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';

@Injectable()
export class MixpanelService {
  private mixpanel: any;

  constructor(private configService: ConfigService) {
    this.mixpanel = Mixpanel.init(
      'mixPanel Project Token', //this.configService.get<string>('mixPanelToken'),
      {
        debug: true,
        protocol: 'http',
      },
    );
  }

  public track(eventName: string, action: any = {}): void {
    this.mixpanel.track(eventName, action);
  }
}

```


app.service

```
import * as ip from 'ip';
import { MixpanelService } from './mixpanel/mixpanel.service';
import { ForbiddenException, Injectable } from '@nestjs/common';

@Injectable()
export class AppService {
  constructor(private readonly mixpanelService: MixpanelService) {}
  async signup(dto: any) {
    try {
      this.mixpanelService.track('Sign Up', {
        $first_name: dto.firstName,
        $last_name: dto.lastName,
        $created: new Date().toISOString(),
        type: 'patient',
        distinct_id: dto.id,
        ip: ip.address(),
      });
      return {
        status: true,
        message: 'User has been created successfully',
        data: dto,
      };
    } catch (err) {
      throw new ForbiddenException({
        status: false,
        message: err.message || 'Error: user not created!',
        error: 'Bad Request',
      });
    }
  }
}
```
That is all folks!
Reference : [Uzeyr OZ](https://dev.to/muzeyr/to-integrate-mixpanel-with-nestjs-1bhl)