To integrate Mixpanel with NestJS, you can use the official Mixpanel JavaScript library and install it via npm:
Install the Mixpanel library:
npm install mixpanel-browser --save
Create a module for Mixpanel by running the following command:
nest generate module mixpanel
In this Mixpanel module, import the Mixpanel library and add it to the imports array:
import { Mixpanel } from 'mixpanel-browser'; @Module({ imports: [ Mixpanel ] }) export class MixpanelModule {}
In the component where you want to use Mixpanel, import the Mixpanel service and initialize it with your Mixpanel token:
import * as mixpanel from 'mixpanel-browser'; import { Injectable } from '@nestjs/common'; import AppConfigService from '../../config/app/configuration.service'; @Injectable() export class MixpanelService { constructor(private readonly configService: AppConfigService) {} init(userToken: string): void { mixpanel.init(this.configService.mixPanelToken); mixpanel.identify(userToken); } track(id: string, action: any = {}): void { mixpanel.track(id, action); } people(id: string, action: any = {}): void { mixpanel.people(id, action); } }
To track an event, use the track method:
constructor( private readonly mixpanelService: MixpanelService, ) {}
example track:
this.mixpanelService.init('UZI'); this.mixpanelService.track('Signup', { $first_name: 'Uz', $last_name: 'Oz', $created: new Date().toISOString(), plan: 'premium', });
To set user properties, use the people.set method:
this.mixpanelService.people.set({ "$email": "joe@example.com", "$first_name": "Joe", "$last_name": "Smith", });
You can also use identify method to identify user with unique ID
this.mixpanelService.identify("13793");
That's it! You have now integrated Mixpanel with your NestJS app using a dedicated Mixpanel module. You can find more information on Mixpanel's official documentation.
Top comments (3)
Hi! Nice write-up.
I tried to use your implementation and ran into some issues. I made a few changes before it worked.
The correct lib to use with NestJs is
npm install mixpanel.
The lib you used in your tutorialnpm install mixpanel-browser
was meant for the web. Your implementation was also for the web instead of Node(NestJs). You might need to make some adjustment to the article.@seunope how did you get this working with nest? i keep getting this error: TypeError: (0 , mixpanel_1.track) is not a function
Why did you use
npm install mixpanel-browser
instead ofnpm install mixpanel
?