npm install @segment/analytics-node
const Analytics = require('@segment/analytics-node');
const analytics = new Analytics('YOUR_WRITE_KEY');
analytics.identify({
userId: 'user123',
traits: {
name: 'John Doe',
email: 'john.doe@example.com',
plan: 'premium',
signupDate: '2024-06-07'
}
});
analytics.track({
userId: 'user123',
event: 'Signed Up',
properties: {
plan: 'premium',
source: 'marketing_campaign'
}
});
analytics.track({
userId: 'user123',
event: 'Logged In',
properties: {
time: '2024-06-07T12:34:56Z'
}
});
analytics.track({
userId: 'user123',
event: 'Subscription Changed',
properties: {
oldPlan: 'basic',
newPlan: 'premium'
}
});
analytics.track({
userId: 'user123',
event: 'Account Deleted',
properties: {
reason: 'user request'
}
});
app.post('/signup', (req, res) => {
const { userId, name, email, plan } = req.body;
// Identify the user
analytics.identify({
userId: userId,
traits: {
name: name,
email: email,
plan: plan,
signupDate: new Date().toISOString()
}
});
// Track the signup event
analytics.track({
userId: userId,
event: 'Signed Up',
properties: {
plan: plan
}
});
res.status(200).send('User signed up successfully');
});
app.post('/login', (req, res) => {
const { userId } = req.body;
// Track the login event
analytics.track({
userId: userId,
event: 'Logged In',
properties: {
time: new Date().toISOString()
}
});
res.status(200).send('User logged in successfully');
});
app.post('/feature-use', (req, res) => {
const { userId, featureName } = req.body;
// Track feature usage
analytics.track({
userId: userId,
event: `Used Feature: ${featureName}`,
properties: {
feature: featureName,
time: new Date().toISOString()
}
});
res.status(200).send('Feature usage recorded');
});
app.post('/subscription-change', (req, res) => {
const { userId, oldPlan, newPlan } = req.body;
// Track the subscription change event
analytics.track({
userId: userId,
event: 'Subscription Changed',
properties: {
oldPlan: oldPlan,
newPlan: newPlan
}
});
res.status(200).send('Subscription change recorded');
});
app.post('/delete-account', (req, res) => {
const { userId, reason } = req.body;
// Track the account deletion event
analytics.track({
userId: userId,
event: 'Account Deleted',
properties: {
reason: reason
}
});
res.status(200).send('Account deletion recorded');
});
By following this guide, startups can efficiently set up Segment to send data from their applications using the Segment SDK. The examples provided demonstrate how to use identify and track calls to capture user traits and events, helping businesses gain valuable insights and make data-driven decisions.