How To Track User Events With Segment in Node.js

February 20, 2026
Written by
Reviewed by

How To Track User Events With Segment in Node.js

Understanding how users interact with your application is essential for building better products and making data-driven decisions. Segment is a customer data platform that simplifies the process of collecting, cleaning, and routing user data to your analytics tools, marketing platforms, and data warehouses.

Instead of implementing multiple analytics libraries and managing separate integrations, Segment provides a single API that lets you send data once and route it to several destinations. This means you can add new analytics tools without changing your codebase.

In this tutorial, you'll learn how to create a Segment source and integrate Segment's Analytics Node.js library into your application to track user events, identify users, and send data to your preferred destinations.

Prerequisites

Client-Side vs Server-Side Tracking

Segment offers two approaches for collecting analytics data: client-side tracking with Analytics.js running in the browser, or server-side tracking with libraries like Analytics for Node.js (which is what this tutorial will use).

This tutorial uses server-side tracking, which gives you full control over what data is sent to Segment and eliminates the need for other scripts in your frontend. If you need automatic client-side tracking, you can use Analytics.js alongside your server implementation.

Setup Application

Create a Segment Source

Before writing any code, you'll need to create a Source in Segment. A Source is where your data originates. For this project, your source will be your Node.js application.

Log in to your Segment workspace and navigate to Connections > Sources from the left panel.

Screenshot of Segment Sources dashboard showing no connected sources and a notice of upcoming maintenance.

Click Add Source, search for Node.js and select it.

Screenshot of Node.js setup page in Twilio Segment showing source details, destination options, and setup requirements.

Once you find Node.js from the catalog, click Add Source and give your source a name (e.g., "My Node App").

Screenshot of the Node.js Server setup page on Twilio Segment, showing installation details and successful receipt status.

Click Add Source and you’ll see your Write Key on the source overview page. This key authenticates your application with Segment.

Take note of the Write Key this as you’ll need it for the next section

Set up a Node.js Application

You'll start setting up your application by initializing a Node.js project, installing the dependencies you'll need and setting environment variables.

Initialize a Node.js project

Open up your terminal, navigate to your preferred directory for Node.js projects, and enter the following commands to create a folder, change into it, and initialize a Node.js project:

mkdir segment-tracking
cd segment-tracking
npm init -y

Install the required dependencies

Next, run the following command to install the dependencies you'll need for this project:

npm install @segment/analytics-node express dotenv
  • @segment/analytics-node - Segment's official Node.js library for tracking events and identifying users
  • express - For building your server and handling HTTP requests
  • dotenv - To load environment variables

Import Environment Variables

Using your preferred text editor or IDE, open up your segment-tracking directory, create a .env file and place the following within the file:

SEGMENT_WRITE_KEY=XXXXXX

Replace XXXXXX with your Write Key from the Segment dashboard (from the previous section) and save the file.

Segment's Core Methods

Before diving into the code, let's understand the six core methods that make up Segment's Spec:

These methods form the foundation of Segment's Spec, a standardized way of structuring your analytics data that ensures consistency across all your tools.

In this tutorial, we'll focus on identify, track, and page, and since they're most relevant for server-side Node.js applications. The screen method is typically used in mobile SDKs, and alias is primarily needed when migrating from other analytics tools or handling specific identity resolution scenarios.

Initialize the Segment Client

Now create a file called index.js within the segment-tracking directory. This file is where you'll write the code to track user events.

Open the index.js file and add the following code to initialize the Segment client:

require('dotenv').config();
const express = require('express');
const { Analytics } = require('@segment/analytics-node');
const app = express();
app.use(express.json());
// Initialize Segment Analytics client
const analytics = new Analytics({
    writeKey: process.env.SEGMENT_WRITE_KEY
});
console.log('Segment client initialized');
// Helper functions (these would connect to your actual database in production)
// For this tutorial, we're using mock implementations to focus on Segment integration
async function createUser({ email, name, password }) {
    // In production, this would save to your database
    const userId = 'user_' + Math.random().toString(36).substring(7);
    return { id: userId, email, name, plan: 'free' };
}
async function processOrder(userId, items, paymentMethod) {
    // In production, this would process payment and create order
    const orderId = 'order_' + Math.random().toString(36).substring(7);
    const total = items.reduce((sum, item) => sum + (item.price || 0), 0);
    return { id: orderId, total, items };
}

This code loads your environment variables, sets up an Express server and creates a new Segment Analytics client using your Write Key.

This code also includes mock helper functions (createUser and processOrder) to demonstrate the Segment integration. In a production application, these functions would interact with your actual database and authentication system.

Identify

The identify method lets you tie a user to their actions and record traits about them. You should call identify when a user first signs up, when they log in, or when their profile information changes.

Add the following signup route to your index.js file:

// User signup route
app.post('/signup', async (req, res) => {
    const { email, name, password } = req.body;
    const user = await createUser({ email, name, password });
    // Identify the user in Segment
    analytics.identify({
        userId: user.id,
        traits: {
            email: email,
            name: name,
            plan: 'free',
            createdAt: new Date().toISOString()
        }
    });
    console.log(`User signed up and identified: ${user.id}`);
    res.status(201).json({ message: 'User created successfully', userId: user.id });
});

The traits object can contain any information about the user that you want to record. Common traits include:

  • email - The user's email address
  • name - The user's full name
  • plan - The user's subscription tier
  • createdAt - When the user account was created
  • company - The user's company name

Track

The track method records specific actions your users perform. Every action triggers an event with a name and optional properties that describe the action. You should call track directly in the route handlers where the action occurs.

For logged-in users, use their userId. For anonymous users, use an anonymousId which you can generate from their session ID or another unique identifier.

In this tutorial, we're passing the userId in the request body for simplicity. In a production application, you would typically use authentication middleware to attach the authenticated user to req.user and generate anonymous IDs using session management libraries like express-session.

Add the following checkout route to your index.js file:

app.post('/checkout', async (req, res) => {
    const { userId, anonymousId, items, paymentMethod } = req.body;
    // Process the order in your system
    const order = await processOrder(userId, items, paymentMethod);
    // Track the completed order
    // Use userId if available, otherwise use anonymousId
    analytics.track({
        userId: userId,
        anonymousId: userId ? undefined : anonymousId,
        event: 'Order Completed',
        properties: {
            orderId: order.id,
            revenue: order.total,
            currency: 'USD',
            products: items,
            paymentMethod: paymentMethod
        }
    });
    console.log(`Order completed for user: ${userId || anonymousId}`);
    res.status(200).json({ message: 'Order placed successfully', orderId: order.id });
});

Page

The page method records whenever a user views a page in your application. This is essential for understanding user navigation patterns, measuring content engagement, and optimizing your user experience. You should call page directly in the route handlers that serve your pages.

Add the following routes to your index.js file:

app.get('/pricing', (req, res) => {
    // In production, userId would come from authentication middleware (req.user)
    // and anonymousId from session cookies or a session management library
    const userId = req.user?.id; // undefined if not authenticated
    const anonymousId = req.session?.id || req.query.anonymousId; // For testing, also accept from query param
    // Track the page view
    // Note: Segment requires at least one identifier (userId or anonymousId)
    analytics.page({
        userId: userId,
        anonymousId: anonymousId,
        name: 'Pricing',
        category: 'Marketing',
        properties: {
            url: req.originalUrl,
            path: req.path,
            referrer: req.get('referer')
        }
    });
    res.json({ message: 'Pricing page viewed' });
});

You can also use middleware to automatically track page views across all routes:

// Middleware to track page views on all GET requests
const trackPageViews = (req, res, next) => {
    // Get userId from authentication middleware (req.user) if available
    // Get anonymousId from session management (req.session) if available
    const userId = req.user?.id;
    const anonymousId = req.session?.id;
    // Track page views for all GET requests
    // Note: Segment requires at least one identifier (userId or anonymousId)
    if (req.method === 'GET' && (userId || anonymousId)) {
        analytics.page({
            userId: userId,
            anonymousId: anonymousId,
            name: req.path,
            properties: {
                url: `${req.protocol}://${req.get('host')}${req.originalUrl}`,
                path: req.path,
                referrer: req.get('referer')
            }
        });
    }
    next();
};
// Apply middleware to all routes
app.use(trackPageViews);

This middleware will track page views only when a userId or anonymousId is available. The check if (req.method === 'GET' && (userId || anonymousId)) ensures we only attempt to track when at least one identifier exists, as required by Segment.

In a production application, you would set up authentication middleware like Passport.js (or custom JWT middleware) to populate req.user, and session management (like express-session) to handle req.session.

Start the Server and Handle Graceful Shutdown

Now that you've added all the routes, you need to start the Express server to listen for incoming requests.

Additionally, Segment's Node.js library batches events and sends them asynchronously for better performance. To ensure all events are sent before your application shuts down, you should flush the client and close it gracefully.

Add the following code to the end of your index.js file:

// Start the server
app.listen(3000, () => {
    console.log(`Server running at port 3000`);
});
// Graceful shutdown handler
process.on('SIGTERM', async () => {
    console.log('Shutting down gracefully...');
    await analytics.closeAndFlush();
    process.exit(0);
});

The app.listen() method starts the Express server on port 3000. The closeAndFlush() method ensures that any queued events are sent to Segment before the process exits when you stop the server.

Test Your Integration

Now it's time to test out your Segment integration. Start your server by running:

node index.js

In a production setting, these endpoints would be called from your frontend application. For example, when a user submits a signup form or clicks a checkout button. For testing purposes, you'll manually send requests using curl to simulate these interactions.

Open a new terminal window and use curl to test your routes.

Sign up a new user (identify method)

Run the following command on your terminal:

curl -X POST http://localhost:3000/signup \
  -H "Content-Type: application/json" \
  -d '{
    "email": "jane@example.com",
    "name": "Jane Doe",
    "password": "securepassword123"
  }'

Complete a checkout (track method)

Run the following command on your terminal:

curl -X POST http://localhost:3000/checkout \
  -H "Content-Type: application/json" \
  -d '{
    "userId": "user_123",
    "items": [{"name": "Pro Plan", "price": 99.99}],
    "paymentMethod": "credit_card"
  }'

View pricing page (page method)

Run the following command on your terminal:

curl "http://localhost:3000/pricing?anonymousId=test_session_12345"

This passes an anonymousId as a query parameter for testing purposes.

View Segment dashboard

After sending these requests, head back to your Segment dashboard and navigate to your Source's Debugger tab. You should see your events appearing in real-time:

Twilio Otpinel UI debugger screen showing marketing pricing data and metadata.

Add Destinations

Now that your events are flowing into Segment, you can route them to any of Segment's destinations. To add a destination:

  1. In your Segment workspace, go to Connections > Destinations
  2. Click Add Destination
  3. Search for and select your preferred destination
  4. Follow the setup instructions for that destination
  5. Connect it to your Node.js source

Once configured, your tracked events will automatically flow to your new destination without any code changes.

What's Next?

You've successfully integrated Segment into your Node.js application and learned how to identify users and track events. Here are some ways to enhance your implementation:

For more advanced use cases, check out Segment's documentation and their Analytics Node.js library reference.

Dhruv Patel is a Developer on Twilio's Developer Voices team. You can find Dhruv working in a coffee shop with a glass of cold brew or he can be reached at dhrpatel [at] twilio.com .