A progressive Node.js framework for building efficient and scalable server-side applications.
Segment Analytics module for Nest
To begin using it, we first install the required dependencies.
$ npm install nestjs-segment-analytics @segment/analytics-nodeOnce the installation process is complete, we can import the SegmentAnalyticsModule. Typically, we'll import it into the root AppModule and control its behavior using the .register() static method. During this step, the segment Analytics instance is created. Later, we'll see how we can access the Analytics instance our other feature modules.
import { SegmentAnalyticsModule } from 'nestjs-segment-analytics';
@Module({
imports: [
SegmentAnalyticsModule.register({
writeKey: '<your key>',
}),
],
providers: [AppService],
})
export class AppModule {}When you want to use SegmentAnalyticsModule in other modules, you'll need to import it (as is standard with any Nest module). Alternatively, declare it as a global module by setting the options object's isGlobal property to true, as shown below. In that case, you will not need to import SegmentAnalyticsModule in other modules once it's been loaded in the root module (e.g., AppModule).
SegmentAnalyticsModule.register({
isGlobal: true,
});Hint The register method accepts all values from
AnalyticsSettingsand passes it to theAnalyticsconstructor, you can see all options here.
To access our segment Analytics instance, we first need to inject Analytics. As with any provider, we need to import its containing module - the SegmentAnalyticsModule - into the module that will use it (unless you set the isGlobal property in the options object passed to the SegmentAnalyticsModule.register() method to true). Import it into a feature module as shown below.
// feature.module.ts
@Module({
imports: [SegmentAnalyticsModule],
// ...
})Then we can inject it using standard constructor injection:
import { InjectAnalytics } from 'nestjs-segment-analytics';
import { Analytics } from '@segment/analytics-node';
// ...
constructor(@InjectAnalytics() private analytics: Analytics) {}HINT The
Analyticsis imported from the@segment/analytics-nodepackage.
And use it in our class:
await this.analytics.track({
userId,
event: 'Create Item',
properties: { itemId: '564897' },
});