nestjs-segment-analytics
v0.0.6
Published
Segment Analytics NestJS Module and Service
Downloads
190
Readme
Description
Segment Analytics module for Nest
Installation
To begin using it, we first install the required dependencies.
$ npm install nestjs-segment-analytics @segment/analytics-node
Getting Started
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.
import { SegmentAnalyticsModule } from 'nestjs-segment-analytics';
@Module({
imports: [
SegmentAnalyticsModule.register({
writeKey: '<your key>',
}),
],
providers: [AppService],
})
export class AppModule {}
Use module globally
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
AnalyticsSettings
and passes it to theAnalytics
constructor, you can see all options here.
Using the ConfigService
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
Analytics
is imported from the@segment/analytics-node
package.
And use it in our class:
await this.analytics.track({
userId,
event: 'Create Item',
properties: { itemId: '564897' },
});