Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Mesonrale Ope
Mesonrale Ope

Posted on

     

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 modeExit 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 modeExit fullscreen mode

Add the following code to themixPanel.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 modeExit fullscreen mode

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

  constructor(    ....    private readonly mixpanelService: MixpanelService,  ) {}
Enter fullscreen modeExit 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 modeExit 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 modeExit 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 modeExit 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 modeExit fullscreen mode

That is all folks!
Reference :Uzeyr OZ

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

  • Joined

Trending onDEV CommunityHot

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp