DEV Community

Mesonrale Ope
Mesonrale Ope

Posted on

2

How to Integrate Mixpanel with NestJS

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

Install the Mixpanel library:

yarn add  mixpanel
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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);
  }
}
Enter fullscreen mode Exit fullscreen mode

To track an event in a module, add the mixPanel service to the module constructor:

  constructor(
    ....
    private readonly mixpanelService: MixpanelService,
  ) {}
Enter fullscreen mode Exit fullscreen mode

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(),
      });
Enter fullscreen mode Exit fullscreen mode

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 {}

Enter fullscreen mode Exit fullscreen mode

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);
  }
}

Enter fullscreen mode Exit fullscreen mode

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',
      });
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

That is all folks!
Reference : Uzeyr OZ

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay