EN VI

Javascript - Mixpanel not working with NestJS, cant find the tracking function?

2024-03-12 20:30:05
How to Javascript - Mixpanel not working with NestJS, cant find the tracking function

I am using mixpanel node (yarn add mixpanel) with NestJS and the only function it seems to recognise is the init function. I am calling this, then trying to call the track function but get the following error:

TypeError: (0 , mixpanel_1.track) is not a function

I have done everything as per the node docs, but can't seem to get this working. Here is the code:

import { init, track } from "mixpanel";
import mixpanelConfig from "../../app/config/mixpanel.config";

init("MYTOKEN", {
  host: "api-eu.mixpanel.com",
  keepAlive: false,
});

@Injectable()
export class MixpanelService {
  constructor(
    @Inject(mixpanelConfig.KEY)
    private readonly mixpanelCfg: ConfigType<typeof mixpanelConfig>,
  ) {
  }
  
  track(name: string, properties?: Record<any, any>) {
    if (this.mixpanelCfg.canTrack && properties) {
      track(name, properties);
    }
  }
}

Solution:

You have to assign the return value of the init function to a variable and use that to call track.

import { init } from "mixpanel";
import mixpanelConfig from "../../app/config/mixpanel.config";

const mixpanel = init("MYTOKEN", {
  host: "api-eu.mixpanel.com",
  keepAlive: false,
});

@Injectable()
export class MixpanelService {
  constructor(
    @Inject(mixpanelConfig.KEY)
    private readonly mixpanelCfg: ConfigType<typeof mixpanelConfig>,
  ) {
  }
  
  track(name: string, properties?: Record<any, any>) {
    if (this.mixpanelCfg.canTrack && properties) {
      mixpanel.track(name, properties);
    }
  }
}
Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login