Segment Sink
The Segment sink sends session data as a track event using your existing @segment/analytics-next client. WriteTrack doesn’t bundle the Segment SDK — you provide your initialized client.
Prerequisites
Section titled “Prerequisites”You need @segment/analytics-next v1.8.0 or later already initialized in your application.
npm i @segment/analytics-nextpnpm add @segment/analytics-nextyarn add @segment/analytics-nextbun add @segment/analytics-nextimport { WriteTrack, segment } from 'writetrack';import { AnalyticsBrowser } from '@segment/analytics-next';
// Initialize Segment (your existing setup)const analytics = AnalyticsBrowser.load({ writeKey: 'YOUR_WRITE_KEY',});
const tracker = new WriteTrack({ target: textarea, userId: 'u_abc123',});
tracker.pipe( segment({ client: analytics, }));
tracker.start();Options
Section titled “Options”| Option | Type | Default | Description |
|---|---|---|---|
client | SegmentClient | — | Initialized Segment analytics client Required |
eventName | string | 'WriteTrack Session' | Custom track event name |
Data Mapping
Section titled “Data Mapping”The sink calls client.track(eventName, properties) with the following properties:
| Property | Source | Description |
|---|---|---|
duration | metadata.duration | Session duration in ms |
keystrokeCount | session.events.length | Total keystroke events |
qualityLevel | quality.qualityLevel | POOR / FAIR / GOOD / EXCELLENT |
targetElement | metadata.targetElement | Element type (e.g. textarea) |
schemaVersion | version | Schema version |
userId | metadata.userId | User ID (if provided) |
contentId | metadata.contentId | Content ID (if provided) |
custom | metadata.custom | Custom metadata (if provided) |
Examples
Section titled “Examples”With Custom Event Name
Section titled “With Custom Event Name”tracker.pipe( segment({ client: analytics, eventName: 'Typing Session Captured', }));Viewing in Segment
Section titled “Viewing in Segment”Track events appear in the Segment Debugger with:
- Event name:
WriteTrack Session(or your custom name) - Properties: duration, keystrokeCount, qualityLevel, etc.
From Segment, the data flows to any connected destination (warehouses, analytics tools, marketing platforms).
Error Handling
Section titled “Error Handling”tracker.on('pipe:error', (err, sink) => { console.error('Segment sink failed:', err);});