Segment Analytics NestJS Module and Service
npm install nestjs-segment-analyticsA 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.
``bash`
$ npm install nestjs-segment-analytics @segment/analytics-node
Once 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.
`typescript
import { SegmentAnalyticsModule } from 'nestjs-segment-analytics';
@Module({
imports: [
SegmentAnalyticsModule.register({
writeKey: '
}),
],
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).
`typescript`
SegmentAnalyticsModule.register({
isGlobal: true,
});
> Hint
> The register method accepts all values from AnalyticsSettings and passes it to the Analytics constructor, 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.
`typescript`
// feature.module.ts
@Module({
imports: [SegmentAnalyticsModule],
// ...
})
Then we can inject it using standard constructor injection:
`typescript
import { InjectAnalytics } from 'nestjs-segment-analytics';
import { Analytics } from '@segment/analytics-node';
// ...
constructor(@InjectAnalytics() private analytics: Analytics) {}
`
> HINT
> The Analytics is imported from the @segment/analytics-node package.
And use it in our class:
`typescript``
await this.analytics.track({
userId,
event: 'Create Item',
properties: { itemId: '564897' },
});