Socket
Socket
Sign inDemoInstall

@segment/analytics-node

Package Overview
Dependencies
17
Maintainers
301
Versions
41
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    @segment/analytics-node

https://www.npmjs.com/package/@segment/analytics-node


Version published
Maintainers
301
Install size
1.69 MB
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

@segment/analytics-node

https://www.npmjs.com/package/@segment/analytics-node

OFFICIAL DOCUMENTATION (FULL)

LEGACY NODE SDK MIGRATION GUIDE:

Runtime Support

  • Node.js >= 14
  • AWS Lambda
  • Cloudflare Workers
  • Vercel Edge Functions
  • Web Workers (experimental)

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'
// or, if you use require:
const { Analytics } = require('@segment/analytics-node')

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

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

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

Settings & Configuration

See the documentation: https://segment.com/docs/connections/sources/catalog/libraries/server/node/#configuration

You can also see the complete list of settings in the AnalyticsSettings interface.

Plugin Architecture

Usage in non-node runtimes

Usage in AWS Lambda

  • AWS lambda execution environment is challenging for typically non-response-blocking async activites like tracking or logging, since the runtime terminates / freezes after a response is emitted.

Here is an example of using analytics.js within a handler:

const { Analytics } = require('@segment/analytics-node');

// since analytics has the potential to be stateful if there are any plugins added,
// to be on the safe side, we should instantiate a new instance of analytics on every request (the cost of instantiation is low).
const analytics = () => new Analytics({
      flushAt: 1,
      writeKey: '<MY_WRITE_KEY>',
    })
    .on('error', console.error);

module.exports.handler = async (event) => {
  ...
  // we need to await before returning, otherwise the lambda will exit before sending the request.
  await new Promise((resolve) =>
    analytics().track({ ... }, resolve)
   )

  ...
  return {
    statusCode: 200,
  };
  ....
};

Usage in Vercel Edge Functions

import { Analytics } from '@segment/analytics-node';
import { NextRequest, NextResponse } from 'next/server';

export const analytics = new Analytics({
  writeKey: '<MY_WRITE_KEY>',
  flushAt: 1,
})
  .on('error', console.error)

export const config = {
  runtime: 'edge',
};

export default async (req: NextRequest) => {
  await new Promise((resolve) =>
    analytics.track({ ... }, resolve)
  );
  return NextResponse.json({ ... })
};

Usage in Cloudflare Workers

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

export default {
  async fetch(
    request: Request,
    env: Env,
    ctx: ExecutionContext
  ): Promise<Response> {
    const analytics = new Analytics({
      flushAt: 1,
      writeKey: '<MY_WRITE_KEY>',
    }).on('error', console.error);

    await new Promise((resolve, reject) =>
      analytics.track({ ... }, resolve)
    );

    ...
    return new Response(...)
  },
};

OAuth 2

In order to guarantee authorized communication between your server environment and Segment's Tracking API, you can enable OAuth 2 in your Segment workspace. To support the non-interactive server environment, the OAuth workflow used is a signed client assertion JWT. You will need a public and private key pair where the public key is uploaded to the segment dashboard and the private key is kept in your server environment to be used by this SDK. Your server will verify its identity by signing a token request and will receive a token that is used to to authorize all communication with the Segment Tracking API.

You will also need to provide the OAuth Application ID and the public key's ID, both of which are provided in the Segment dashboard. You should ensure that you are implementing handling for Analytics SDK errors. Good logging will help distinguish any configuration issues.

import { Analytics, OAuthSettings } from '@segment/analytics-node';
import { readFileSync } from 'fs'

const privateKey = readFileSync('private.pem', 'utf8')

const settings: OAuthSettings = {
  clientId: '<CLIENT_ID_FROM_DASHBOARD>',
  clientKey: privateKey,
  keyId: '<PUB_KEY_ID_FROM_DASHBOARD>',
}

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

analytics.on('error', (err) => { console.error(err) })

analytics.track({ userId: 'foo', event: 'bar' })

FAQs

Last updated on 29 Jan 2024

Did you know?

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