@segment/analytics-node
TypeScript icon, indicating that this package has built-in type declarations

2.1.1 • Public • Published

@segment/analytics-node

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

OFFICIAL DOCUMENTATION (FULL)

LEGACY NODE SDK MIGRATION GUIDE:

Runtime Support

  • Node.js >= 18
  • AWS Lambda
  • Cloudflare Workers
  • Vercel Edge Functions
  • Web Workers / Browser (no device mode destination support)

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

Readme

Keywords

none

Package Sidebar

Install

npm i @segment/analytics-node

Weekly Downloads

325,382

Version

2.1.1

License

MIT

Unpacked Size

252 kB

Total Files

192

Last publish

Collaborators

  • ssuneja
  • azhaotwilio
  • ldelossantos
  • cjo2
  • achandrashekaran
  • aparna.singhal
  • ynguyen
  • timmyzsearcy
  • igracheva-twilio
  • yashnit-segment
  • nanotimm
  • srivig21
  • chenchensegmentcom
  • sanket.mishra
  • lweimersegment
  • rcheedhalla
  • jxin_twilio
  • odoren_segment
  • aditi.raveesh
  • dltnbrks-segment
  • sai-patanjali
  • himanshuph
  • alecjacobs-segment
  • sshaikh_segment
  • john.lee1100
  • dazu70
  • brian.aguirre
  • pooja.patil
  • segment_fan
  • nlubchenco
  • jamezhutwilio
  • knksmith57-segment
  • jsh-wu
  • nithin-benny
  • poojasegment
  • ebru.odok
  • bannapple
  • rodhilton_twilio
  • guthriesegment
  • srishti-nema
  • cdelaomartinez
  • miguelpdiaz8
  • sundareswar.jayakumar
  • gbatra
  • spencerattick
  • akodankiry
  • nanette.ranes
  • gsolis_segment
  • nitinpm432
  • aadityabhatt10
  • amigandhi
  • segmentsean
  • hmohanram_seg
  • jrupasinghe
  • myrontin.segment
  • devthale
  • smccoy-twilio
  • seg-leonelsanches
  • jibrang
  • sethgrid_segment
  • light-bringer-blr
  • aubreysine
  • ed-twilion-npm
  • harsh-joshi99
  • irfan.ali.segment
  • kbhargavaram-sg
  • needcaffeine
  • nat-grid
  • wlumsegment
  • vivek-26
  • moyara2
  • bala.singareddy
  • gbbastos
  • akash.gautam07
  • preetyp
  • viveksainaneesegment
  • msaraf
  • kjoerres
  • rokatyal
  • ainatancinco
  • anton-vylushchak
  • sowjanyasegment
  • alayvora
  • msaunders-segment
  • tw-dgarcia
  • parag.panda
  • blangtwilio
  • ryanrouleau-segment
  • twjosiah
  • mcullenmeyer
  • david.anusontarangkul.segment
  • mckern_segment
  • segment-admin
  • nainy.agrawal
  • tdibacco
  • sudojatin
  • nageshgolem
  • brandonheyer-segment
  • alfrimpong
  • dobrin.ganev
  • ankit.gupta.unthinkable
  • marinhero
  • benattwilio
  • bharath.boregowda
  • conniechen
  • sungju.jin
  • pooyaj
  • yli119
  • ea_segment
  • emilyjia
  • kx-segment
  • xinghao.huang
  • harsh.vardhan
  • joe.ayoub.segment
  • gkochar123
  • rollcode
  • ariel.silvestri
  • cherylj-segment
  • immanoj
  • aaronklish
  • michelr
  • maneesh.dharma29
  • msolorzano-segment
  • brianhumphreystwilio
  • jfehrman.segment
  • joetessy
  • pmunin
  • jalexy12
  • jbandi-twilio
  • prayansh-twilio
  • dominicbarnes
  • brandon.scott-segment
  • bgillan
  • phillip.thomas
  • ricardo.rossi
  • forgetfulfellow
  • fauzy.yy
  • mayur-pitale
  • dbaik-twilio-segment
  • seg-rustybailey
  • tanya.gupta.segment
  • pmiller-twilio
  • nevermore2022
  • aishikawaki
  • csayuso
  • mcoulibali
  • shupadhyay
  • jahood-twilio
  • saisagarkappaganthula
  • rmukundan
  • arubiochavez
  • shuvrajit9904
  • s3gm3nt
  • ama0223
  • tbrennanj
  • dangmai-segment
  • shraddha-twilio
  • sa-jsooter
  • enyi.asonye
  • afsha-nazim-seg
  • mschaszberger
  • lnamba
  • varadarajan-tw
  • seanhan-segment
  • replatero
  • sayan-das-in
  • justeen
  • sausingh
  • jgabe13
  • meg1000
  • funlu
  • ashwitha.bg
  • whaider_twilio
  • tcgilbert
  • kevinburkesegment
  • felttrip
  • prabhnoor1997
  • akashyap91
  • clintz.seg
  • karimkeshwani
  • wally.tg
  • rhall-twilio
  • yash-twilio
  • brookstaylorjr
  • shayan-golafshani
  • lerahulram
  • mugelstad
  • hdamani
  • rrivera-segment
  • sethnutetwilio
  • manali-bhosale
  • chtoombs
  • sethsegment
  • eric-hyde
  • elmoselyee
  • michaelghseg
  • jayakrishnannair
  • lateefat
  • maryam.sharif
  • wdbetts
  • ryanligon
  • sindhusegment
  • lfdelossantos
  • aramakrishnan
  • segment-camden
  • vbatanov
  • lluque-twilio
  • jair.aviles
  • pmaid
  • song4you
  • peterdemartini
  • emmy.byrne
  • vincen7tran
  • dean-huynh
  • cdignam-segment
  • abhinavsureka
  • arunlalam-segment
  • cjradek
  • neeharikakondipati
  • simpixelated
  • chihchun-twilio
  • acharles14
  • jyim008
  • hema-segment
  • oscb
  • krousseau
  • sachinwathore
  • fhalim-segment
  • cfree
  • hjoonpm
  • celine-segment
  • pmcanseco-segment
  • masira
  • amillet89
  • cholt002
  • av-segment
  • aghotikar
  • vikrant-segment
  • larryatsegment
  • ariel_segment
  • scruwys1
  • kyliepedersen
  • jinapark
  • segmentio
  • rajulvadera
  • lpediredla
  • n2parko
  • tyson_segment
  • bgamwell
  • uditmehta
  • salolivares
  • erikdw
  • chenxiangzhang
  • mericsson
  • prayansh-segmentt
  • jeremylarkin
  • bsneed
  • danieljackins
  • segment-seth
  • james9446
  • priscilla.giatti
  • nlsun
  • drew-thompson
  • segment-jsingh
  • andrius-segment
  • valerieernst
  • kelcook
  • gilomer
  • marcelopv
  • eric.rogner
  • kdharaiya
  • jon.anderson-at-segment.com
  • stacy.song
  • rexatsegment
  • nickaguilar
  • bradenbecker
  • reneewang
  • dan.lasky
  • sam.tapia
  • vikramkumar19
  • mpriyad25
  • jeremy.parker
  • smidges