npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@segment/analytics-next

v1.66.0

Published

Analytics Next (aka Analytics 2.0) is the latest version of Segment’s JavaScript SDK - enabling you to send your data to any tool without having to learn, test, or use a new API every time.

Downloads

1,980,457

Maintainers

cjo2cjo2achandrashekaranachandrashekaranaparna.singhalaparna.singhalynguyenynguyentimmyzsearcytimmyzsearcyigracheva-twilioigracheva-twilioyashnit-segmentyashnit-segmentnanotimmnanotimmsrivig21srivig21chenchensegmentcomchenchensegmentcomsanket.mishrasanket.mishralweimersegmentlweimersegmentrcheedhallarcheedhallajxin_twiliojxin_twilioodoren_segmentodoren_segmentaditi.raveeshaditi.raveeshdltnbrks-segmentdltnbrks-segmentsai-patanjalisai-patanjalihimanshuphhimanshuphalecjacobs-segmentalecjacobs-segmentsshaikh_segmentsshaikh_segmentjohn.lee1100john.lee1100dazu70dazu70brian.aguirrebrian.aguirrepooja.patilpooja.patilsegment_fansegment_fannlubchenconlubchencojamezhutwiliojamezhutwilioknksmith57-segmentknksmith57-segmentjsh-wujsh-wunithin-bennynithin-bennypoojasegmentpoojasegmentebru.odokebru.odokbannapplebannapplerodhilton_twiliorodhilton_twilioguthriesegmentguthriesegmentsrishti-nemasrishti-nemacdelaomartinezcdelaomartinezmiguelpdiaz8miguelpdiaz8sundareswar.jayakumarsundareswar.jayakumargbatragbatraspencerattickspencerattickakodankiryakodankirynanette.ranesnanette.ranesgsolis_segmentgsolis_segmentnitinpm432nitinpm432aadityabhatt10aadityabhatt10amigandhiamigandhisegmentseansegmentseanhmohanram_seghmohanram_segjrupasinghejrupasinghemyrontin.segmentmyrontin.segmentdevthaledevthalesmccoy-twiliosmccoy-twilioseg-leonelsanchesseg-leonelsanchesjibrangjibrangsethgrid_segmentsethgrid_segmentlight-bringer-blrlight-bringer-blraubreysineaubreysineed-twilion-npmed-twilion-npmharsh-joshi99harsh-joshi99irfan.ali.segmentirfan.ali.segmentkbhargavaram-sgkbhargavaram-sgneedcaffeineneedcaffeinenat-gridnat-gridwlumsegmentwlumsegmentvivek-26vivek-26moyara2moyara2bala.singareddybala.singareddygbbastosgbbastosakash.gautam07akash.gautam07preetyppreetypviveksainaneesegmentviveksainaneesegmentmsarafmsarafkjoerreskjoerresrokatyalrokatyalainatancincoainatancincoanton-vylushchakanton-vylushchaksowjanyasegmentsowjanyasegmentalayvoraalayvoramsaunders-segmentmsaunders-segmenttw-dgarciatw-dgarciaparag.pandaparag.pandablangtwilioblangtwilioryanrouleau-segmentryanrouleau-segmenttwjosiahtwjosiahmcullenmeyermcullenmeyerdavid.anusontarangkul.segmentdavid.anusontarangkul.segmentmckern_segmentmckern_segmentsegment-adminsegment-adminnainy.agrawalnainy.agrawaltdibaccotdibaccosudojatinsudojatinnageshgolemnageshgolembrandonheyer-segmentbrandonheyer-segmentalfrimpongalfrimpongdobrin.ganevdobrin.ganevankit.gupta.unthinkableankit.gupta.unthinkablemarinheromarinherobenattwiliobenattwiliobharath.boregowdabharath.boregowdaconniechenconniechensungju.jinsungju.jinpooyajpooyajyli119yli119ea_segmentea_segmentemilyjiaemilyjiakx-segmentkx-segmentcvillela_segmentcvillela_segmentxinghao.huangxinghao.huangharsh.vardhanharsh.vardhanjoe.ayoub.segmentjoe.ayoub.segmentgkochar123gkochar123rollcoderollcodeariel.silvestriariel.silvestricherylj-segmentcherylj-segmentleifdreizlerleifdreizlerimmanojimmanojaaronklishaaronklishmichelrmichelrmaneesh.dharma29maneesh.dharma29msolorzano-segmentmsolorzano-segmentbrianhumphreystwiliobrianhumphreystwiliojfehrman.segmentjfehrman.segmentjoetessyjoetessypmuninpmuninjalexy12jalexy12jbandi-twiliojbandi-twilioprayansh-twilioprayansh-twiliodominicbarnesdominicbarnesbrandon.scott-segmentbrandon.scott-segmentbgillanbgillanphillip.thomasphillip.thomasricardo.rossiricardo.rossiforgetfulfellowforgetfulfellowfauzy.yyfauzy.yymayur-pitalemayur-pitaledbaik-twilio-segmentdbaik-twilio-segmentseg-rustybaileyseg-rustybaileytanya.gupta.segmenttanya.gupta.segmentpmiller-twiliopmiller-twilionevermore2022nevermore2022aishikawakiaishikawakicsayusocsayusomcoulibalimcoulibalishupadhyayshupadhyayjahood-twiliojahood-twiliosaisagarkappaganthulasaisagarkappaganthularmukundanrmukundanarubiochavezarubiochavezshuvrajit9904shuvrajit9904s3gm3nts3gm3ntama0223ama0223tbrennanjtbrennanjdangmai-segmentdangmai-segmentshraddha-twilioshraddha-twilioazhaotwilioazhaotwiliosa-jsootersa-jsooterenyi.asonyeenyi.asonyeafsha-nazim-segafsha-nazim-segmschaszbergermschaszbergerlnambalnambavaradarajan-twvaradarajan-twseanhan-segmentseanhan-segmentreplateroreplaterosayan-das-insayan-das-injusteenjusteensausinghsausinghjgabe13jgabe13meg1000meg1000funlufunluashwitha.bgashwitha.bgwhaider_twiliowhaider_twiliotcgilberttcgilbertkevinburkesegmentkevinburkesegmentfelttripfelttripprabhnoor1997prabhnoor1997akashyap91akashyap91clintz.segclintz.segkarimkeshwanikarimkeshwaniwally.tgwally.tgrhall-twiliorhall-twilioyash-twilioyash-twiliobrookstaylorjrbrookstaylorjrshayan-golafshanishayan-golafshanilerahulramlerahulrammugelstadmugelstadhdamanihdamanirrivera-segmentrrivera-segmentsethnutetwiliosethnutetwiliomanali-bhosalemanali-bhosalechtoombschtoombssethsegmentsethsegmenteric-hydeeric-hydeelmoselyeeelmoselyeemichaelghsegmichaelghsegjayakrishnannairjayakrishnannairlateefatlateefatmaryam.sharifmaryam.sharifwdbettswdbettsryanligonryanligonsindhusegmentsindhusegmentlfdelossantoslfdelossantosaramakrishnanaramakrishnansegment-camdensegment-camdenvbatanovvbatanovlluque-twiliolluque-twiliojair.avilesjair.avilespmaidpmaidsong4yousong4youpeterdemartinipeterdemartiniemmy.byrneemmy.byrnevincen7tranvincen7trandean-huynhdean-huynhcdignam-segmentcdignam-segmentabhinavsurekaabhinavsurekaarunlalam-segmentarunlalam-segmentcjradekcjradekneeharikakondipatineeharikakondipatisimpixelatedsimpixelatedchihchun-twiliochihchun-twilioacharles14acharles14jyim008jyim008hema-segmenthema-segmentoscboscbkrousseaukrousseausachinwathoresachinwathorefhalim-segmentfhalim-segmentcfreecfreehjoonpmhjoonpmceline-segmentceline-segmentpmcanseco-segmentpmcanseco-segmentmasiramasiraamillet89amillet89cholt002cholt002av-segmentav-segmentaghotikaraghotikarvikrant-segmentvikrant-segmentlarryatsegmentlarryatsegmentariel_segmentariel_segmentscruwys1scruwys1lew-gordonlew-gordonkyliepedersenkyliepedersenjinaparkjinaparksegmentiosegmentiorajulvaderarajulvaderalpediredlalpediredlan2parkon2parkotyson_segmenttyson_segmentbgamwellbgamwelluditmehtauditmehtasalolivaressalolivareserikdwerikdwchenxiangzhangchenxiangzhangmericssonmericssonprayansh-segmenttprayansh-segmenttjeremylarkinjeremylarkinbsneedbsneeddanieljackinsdanieljackinssegment-sethsegment-sethjames9446james9446priscilla.giattipriscilla.giattikellylukellylunlsunnlsundrew-thompsondrew-thompsonsegment-jsinghsegment-jsinghandrius-segmentandrius-segmentvalerieernstvalerieernstkelcookkelcookgilomergilomermarcelopvmarcelopveric.rognereric.rognerkdharaiyakdharaiyajon.anderson-at-segment.comjon.anderson-at-segment.comstacy.songstacy.songrexatsegmentrexatsegmentnickaguilarnickaguilarbradenbeckerbradenbeckerreneewangreneewangdan.laskydan.laskysam.tapiasam.tapiavikramkumar19vikramkumar19mpriyad25mpriyad25jeremy.parkerjeremy.parkersmidgessmidges

Keywords

Readme

@segment/analytics-next

Analytics Next (aka Analytics 2.0) is the latest version of Segment’s JavaScript SDK - enabling you to send your data to any tool without having to learn, test, or use a new API every time.

Table of Contents


🏎️ Quickstart

The easiest and quickest way to get started with Analytics 2.0 is to use it through Segment. Alternatively, you can install it through NPM and do the instrumentation yourself.

💡 Using with Segment

  1. Create a javascript source at Segment - new sources will automatically be using Analytics 2.0! Segment will automatically generate a snippet that you can add to your website. For more information visit our documentation).

  2. Start tracking!

💻 Using as an npm package

  1. Install the package
# npm
npm install @segment/analytics-next

# yarn
yarn add @segment/analytics-next

# pnpm
pnpm add @segment/analytics-next
  1. Import the package into your project and you're good to go (with working types)!
import { AnalyticsBrowser } from '@segment/analytics-next'

const analytics = AnalyticsBrowser.load({ writeKey: '<YOUR_WRITE_KEY>' })

analytics.identify('hello world')

document.body?.addEventListener('click', () => {
  analytics.track('document body clicked!')
})

Lazy / Delayed Loading

You can load a buffered version of analytics that requires .load to be explicitly called before initiating any network activity. This can be useful if you want to wait for a user to consent before fetching any tracking destinations or sending buffered events to segment.

  • ⚠️ ️.load should only be called once.
export const analytics = new AnalyticsBrowser()

analytics.identify("hello world")

if (userConsentsToBeingTracked) {
    analytics.load({ writeKey: '<YOUR_WRITE_KEY>' }) // destinations loaded, enqueued events are flushed
}

This strategy also comes in handy if you have some settings that are fetched asynchronously.

const analytics = new AnalyticsBrowser()
fetchWriteKey().then(writeKey => analytics.load({ writeKey }))

analytics.identify("hello world")

Error Handling

Handling initialization errors

Initialization errors get logged by default, but if you also want to catch these errors, you can do the following:

export const analytics = new AnalyticsBrowser();
analytics
  .load({ writeKey: "MY_WRITE_KEY" })
  .catch((err) => ...);

Custom CDN / API Proxy

Self Hosting or Proxying Analytics.js documentation

Examples / Usage in Common Frameworks and SPAs

Next.js

  • https://github.com/vercel/next.js/tree/canary/examples/with-segment-analytics
  • https://github.com/vercel/next.js/tree/canary/examples/with-segment-analytics-pages-router

Vanilla React

import { AnalyticsBrowser } from '@segment/analytics-next'

// We can export this instance to share with rest of our codebase.
export const analytics = AnalyticsBrowser.load({ writeKey: '<YOUR_WRITE_KEY>' })

const App = () => (
  <div>
    <button onClick={() => analytics.track('hello world')}>Track</button>
  </div>
)

Vue

  1. Export analytics instance.
import { AnalyticsBrowser } from '@segment/analytics-next'

export const analytics = AnalyticsBrowser.load({
  writeKey: '<YOUR_WRITE_KEY>',
})
  1. in .vue component
<template>
  <button @click="track()">Track</button>
</template>

<script>
import { defineComponent } from 'vue'
import { analytics } from './services/segment'

export default defineComponent({
  setup() {
    function track() {
      analytics.track('Hello world')
    }

    return {
      track,
    }
  },
})
</script>

Support for Web Workers (Experimental)

While this package does not support web workers out of the box, there are options:

  1. Run analytics.js in a web worker via partytown.io. See our partytown example. Supports both cloud and device mode destinations, but not all device mode destinations may work.

  2. Try @segment/analytics-node with flushAt: 1, which should work in any runtime where fetch is available. Warning: cloud destinations only!

How to add typescript support (snippet users only)

  1. Install npm package @segment/analytics-next as a dev dependency.

  2. Create ./typings/analytics.d.ts

// ./typings/analytics.d.ts
import type { AnalyticsSnippet } from "@segment/analytics-next";

declare global {
  interface Window {
    analytics: AnalyticsSnippet;
  }
}
  1. Configure typescript to read from the custom ./typings folder
// tsconfig.json
{
  ...
  "compilerOptions": {
    ....
    "typeRoots": [
      "./node_modules/@types",
      "./typings"
    ]
  }
  ....
}

🐒 Development

First, clone the repo and then startup our local dev environment:

$ git clone [email protected]:segmentio/analytics-next.git
$ cd analytics-next
$ nvm use  # installs correct version of node defined in .nvmrc.
$ yarn && yarn build
$ yarn test
$ yarn dev  # optional: runs analytics-next playground.

If you get "Cannot find module '@segment/analytics-next' or its corresponding type declarations.ts(2307)" (in VSCode), you may have to "cmd+shift+p -> "TypeScript: Restart TS server"

Then, make your changes and test them out in the test app!

🔌 Plugins

When developing against Analytics Next you will likely be writing plugins, which can augment functionality and enrich data. Plugins are isolated chunks which you can build, test, version, and deploy independently of the rest of the codebase. Plugins are bounded by Analytics Next which handles things such as observability, retries, and error management.

Plugins can be of two different priorities:

  1. Critical: Analytics Next should expect this plugin to be loaded before starting event delivery
  2. Non-critical: Analytics Next can start event delivery before this plugin has finished loading

and can be of five different types:

  1. Before: Plugins that need to be run before any other plugins are run. An example of this would be validating events before passing them along to other plugins.
  2. After: Plugins that need to run after all other plugins have run. An example of this is the segment.io integration, which will wait for destinations to succeed or fail so that it can send its observability metrics.
  3. Destination: Destinations to send the event to (ie. legacy destinations). Does not modify the event and failure does not halt execution.
  4. Enrichment: Modifies an event, failure here could halt the event pipeline.
  5. Utility: Plugins that change Analytics Next functionality and don't fall into the other categories.

Here is an example of a simple plugin that would convert all track events event names to lowercase before the event gets sent through the rest of the pipeline:

import type { Plugin } from '@segment/analytics-next'

export const lowercase: Plugin = {
  name: 'Lowercase Event Name',
  type: 'before',
  version: '1.0.0',

  isLoaded: () => true,
  load: () => Promise.resolve(),

  track: (ctx) => {
    ctx.event.event = ctx.event.event.toLowerCase()
    return ctx
  }
}

analytics.register(lowercase)

For further examples check out our existing plugins.

🧪 QA

Feature work and bug fixes should include tests. Run all Jest tests:

$ yarn test

Lint all with ESLint:

$ yarn lint