@askeladden/segment-node
v1.2.1
Published
For analytics with [Segment](https://segment.com/docs/?ref=nav) 🔥
Downloads
28
Readme
Segment Node
For analytics with Segment 🔥
Can be used both in a node environment amd as a react hook!
React
When using the react hook, browser cookies, page data ++ are automatically parsed and added to every event
import { useSegment } from '@askeladden/segment-node';
function UselessComponent() {
const [user, setUser] = useState({ id: 'userId', email: '[email protected]' })
const segment = useSegment({ writeKey: '<SEGMENT_WRITE_KEY>', });
const track = useCallback(async () => {
// create a user object to track
const segmentUser = segment.user(user.id).withUserTraits({
email: user.email,
});
// track an event, and include the user traits
await segmentUser.trackWithUserTraits('Clicked button', {
buttonName: 'Red button',
});
}, [segment]);
return <button onclick={track}>Red button</button>
}Node
import { SegmentNode } from '@askeladden/segment-node';
const segment = new SegmentNode({ writeKey: '<SEGMENT_WRITE_KEY>' });
const httpHandler = (req, res) => {
const user = getUserFromDb();
const segmentUser = segment.user(user.id)
// automatically retrieve cookies, ip, page url ++ from the request headers
.withRequest(req);
.withUserTraits({
email: user.email,
})
// track an event, and include the user traits
await segmentUser.trackWithUserTraits('Did backend event', {
backendData: 'super secret',
})
}Documentation on segment.user(id)
This makes track events include user data as context, which is useful for marketing in Klaviyo ++.
const segmentUser = segment.user(customer.id).withUserTraits
Include user traits with requests. This can be anything, but segment has some pre-defined values that they automatically map to their connected destinations (https://segment.com/docs/connections/spec/identify/). These are typed to provide intellisense completion in your editor.
const segmentUser = segment
.user(user.id)
.withUserTraits({
// your user data
});.withRequest (node only)
Optionally include a Next/Vercel request as context. This automatically parses cookies from Facebook and Google, and maps them to the correct destinations in segment
const segmentUser = segment
.user(user.id)
.withRequest(req)
.withUserTraits({
// your user data
});.withCookies
To manually provide browser cookies, you can use .withCookies. When using the react hook useSegment this happens automatically.
const segmentUser = segment
.user(user.id)
.withCookies({
_ga: 'GA1.2.247765882.1631567939',
_fbp: 'fb.1.1639937056707.1125477210',
});Identify the user
await segmentUser.identify();Group the user
await segmentUser.group(customer.organization_number, {
// company/group traits
});Track the user
await segmentUser.track('Booked Appointment', {
// booking data
});To automatically include the user traits in the event properties, use trackWithUserTraits.
await segmentUser.trackWithUserTraits('Booked Appointment', {
// booking data
});