Socket
Socket
Sign inDemoInstall

@segment/analytics-node

Package Overview
Dependencies
3
Maintainers
223
Versions
41
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

@segment/analytics-node


Version published
Maintainers
223
Created

Package description

What is @segment/analytics-node?

@segment/analytics-node is a Node.js client for Segment, a customer data platform that helps you collect, clean, and control your customer data. This package allows you to send data from your Node.js applications to Segment, which can then route it to various analytics and marketing tools.

What are @segment/analytics-node's main functionalities?

Track

The `track` method allows you to record any actions your users perform. It is useful for tracking events like purchases, sign-ups, or any other user activity.

const Analytics = require('@segment/analytics-node');
const analytics = new Analytics('YOUR_WRITE_KEY');

analytics.track({
  userId: 'user123',
  event: 'Item Purchased',
  properties: {
    item: 'T-shirt',
    price: 19.99
  }
});

Identify

The `identify` method lets you tie a user to their actions and record traits about them. This is useful for associating user data like name, email, and other attributes.

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'
  }
});

Group

The `group` method allows you to associate an individual user with a group, such as a company or organization. This is useful for B2B applications where you need to track users within the context of their organization.

const Analytics = require('@segment/analytics-node');
const analytics = new Analytics('YOUR_WRITE_KEY');

analytics.group({
  userId: 'user123',
  groupId: 'group123',
  traits: {
    name: 'Company Inc.',
    industry: 'Technology'
  }
});

Page

The `page` method is used to record page views on your website. This is useful for tracking which pages your users are visiting.

const Analytics = require('@segment/analytics-node');
const analytics = new Analytics('YOUR_WRITE_KEY');

analytics.page({
  userId: 'user123',
  category: 'Docs',
  name: 'Node.js SDK',
  properties: {
    url: 'https://example.com/docs/nodejs-sdk'
  }
});

Alias

The `alias` method is used to merge two user identities, effectively linking an anonymous user with an identified user. This is useful for scenarios where a user initially interacts anonymously and later signs up or logs in.

const Analytics = require('@segment/analytics-node');
const analytics = new Analytics('YOUR_WRITE_KEY');

analytics.alias({
  previousId: 'temp_user123',
  userId: 'user123'
});

Other packages similar to @segment/analytics-node

Readme

Source

Warning: Until 1.x release, use this library at your own risk!

While the API is very similar, the documentation for the legacy SDK (analytics-node) is here: https://segment.com/docs/connections/sources/catalog/libraries/server/node/

Quick Start

Install library

# npm
npm install @segment/analytics-node
# yarn
yarn add @segment/analytics-node
# pnpm
pnpm install @segment/analytics-node

Usage (assuming some express-like web framework)

import { Analytics } from '@segment/analytics-node'

const analytics = new Analytics({ writeKey: '<MY_WRITE_KEY>' })


app.post('/login', (req, res) => {
   analytics.identify({
      userId: req.body.userId,
      previousId: req.body.previousId
  })
})

app.post('/cart', (req, res) => {
  analytics.track({
    userId: req.body.userId,
    event: 'Add to cart',
    properties: { productId: '123456' }
  })
});

Complete Settings / Configuration

See complete list of settings in the AnalyticsSettings interface.

new Analytics({
    writeKey: '<MY_WRITE_KEY>',
    host: 'https://api.segment.io',
    path: '/v1/batch',
    flushInterval: 10000,
    plugins: [plugin1, plugin2],
    // ... and more!
  })

Graceful Shutdown

Avoid losing events on exit!

  • Call .closeAndFlush() to stop collecting new events and flush all existing events.
  • If a callback on an event call is included, this also waits for all callbacks to be called, and any of their subsequent promises to be resolved.
await analytics.closeAndFlush()
// or
await analytics.closeAndFlush({ timeout: 5000 }) // force resolve after 5000ms

Graceful Shutdown: Advanced Example

import { Analytics } from '@segment/analytics-node'
import express from 'express'

const analytics = new Analytics({ writeKey: '<MY_WRITE_KEY>' })

const app = express()
app.post('/cart', (req, res) => {
  analytics.track({
    userId: req.body.userId,
    event: 'Add to cart',
    properties: { productId: '123456' }
  })
});

const server = app.listen(3000)


const onExit = async () => {
  console.log("Gracefully closing server...");
  await analytics.closeAndFlush() // flush all existing events
  server.close(() => process.exit());
};

process.on("SIGINT", onExit);
process.on("SIGTERM", onExit);
Collecting unflushed events

If you absolutely need to preserve all possible events in the event of a forced timeout, even ones that came in after analytics.closeAndFlush() was called, you can collect those events.

const unflushedEvents = []

analytics.on('call_after_close', (event) => unflushedEvents.push(events))
await analytics.closeAndFlush()

console.log(unflushedEvents) // all events that came in after closeAndFlush was called

Event Emitter

// listen globally to events
analytics.on('identify', (ctx) => console.log(ctx.event))

// listen for errors (if needed)
analytics.on('error', (err) => console.error(err))

FAQs

Last updated on 10 Nov 2022

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc