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

    1.33.4 • Public • Published

    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)! Example react app:
    import { Analytics, AnalyticsBrowser, Context } from '@segment/analytics-next'
    import { useEffect, useState } from 'react'
    import logo from './logo.svg'
    
    function App() {
      const [analytics, setAnalytics] = useState<Analytics | undefined>(undefined)
      const [writeKey, setWriteKey] = useState('<YOUR_WRITE_KEY>')
    
      useEffect(() => {
        const loadAnalytics = async () => {
          let [response] = await AnalyticsBrowser.load({ writeKey })
          setAnalytics(response)
        }
        loadAnalytics()
      }, [writeKey])
    
      return (
        <div className="App">
          <header className="App-header">
            <img src={logo} className="App-logo" alt="logo" />
            <p>
              Edit <code>src/App.js</code> and save to reload.
            </p>
            <a
              onClick={(e) => {
                e.preventDefault()
                analytics?.track('Hello world')
              }}
              className="App-link"
              href="https://reactjs.org"
              target="_blank"
              rel="noopener noreferrer"
            >
              Track
            </a>
          </header>
        </div>
      )
    }
    
    export default App

    using Vite with Vue 3

    1. add to your index.html
    <script>
      window.global = window
      var exports = {}
    </script>
    1. create composable file segment.ts with factory ref analytics:
    import { ref, reactive } from 'vue'
    import { Analytics, AnalyticsBrowser } from '@segment/analytics-next'
    
    const analytics = ref<Analytics>()
    
    export const useSegment = () => {
      if (!analytics.value) {
        AnalyticsBrowser.load({
          writeKey: '<YOUR_WRITE_KEY>',
        })
          .then(([response]) => {
            analytics.value = response
          })
          .catch((e) => {
            console.log('error loading segment')
          })
      }
    
      return reactive({
        analytics,
      })
    }
    1. in component
    <template>
      <button @click="track()">Track</button>
    </template>
    
    <script>
    import { defineComponent } from 'vue'
    import { useSegment } from './services/segment'
    
    export default defineComponent({
      setup() {
        const { analytics } = useSegment()
        
        function track() { 
          analytics?.track('Hello world')
        }
        
        return {
          track
        }
      }
    })
    </script>
    

    🐒 Development

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

    $ git clone git@github.com:segmentio/analytics-next.git
    $ cd analytics-next
    $ make dev

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

    Example of the development 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:

    export const lowercase: Plugin = {
      name: 'Lowercase events',
      type: 'before',
      version: '1.0.0',
    
      isLoaded: () => true,
      load: () => Promise.resolve(),
    
      track: (ctx) => {
        ctx.event.event = ctx.event.event.toLowerCase()
        return ctx
      },
      identify: (ctx) => ctx,
      page: (ctx) => ctx,
      alias: (ctx) => ctx,
      group: (ctx) => ctx,
      screen: (ctx) => ctx,
    }

    For further examples check out our existing plugins.

    🧪 Testing

    The tests are written in Jest and can be run be using make test-unit Linting is done using ESLint and can be run using make lint.

    Unit Testing

    Please write small, and concise unit tests for every feature you work on.

    $ make test-unit # runs all tests
    $ yarn jest src/<path> # runs a specific test or tests in a folder

    Keywords

    none

    Install

    npm i @segment/analytics-next

    DownloadsWeekly Downloads

    20,111

    Version

    1.33.4

    License

    MIT

    Unpacked Size

    4.97 MB

    Total Files

    849

    Last publish

    Collaborators

    • sweetslush
    • jair.aviles
    • rfarivar
    • pmaid
    • song4you
    • peterdemartini
    • emmy.byrne
    • ashkon
    • vincen7tran
    • ariel.silvestri
    • xinghaohuang
    • dean-huynh
    • cdignam-segment
    • bkambo
    • abhinavsureka
    • rikezatsegment
    • arunlalam-segment
    • cjradek
    • neeharikakondipati
    • simpixelated
    • chihchun-twilio
    • sangeeta.singh
    • acharles14
    • jyim008
    • seghungtran
    • alayvora
    • tv0
    • pchen-twilio
    • hema-segment
    • sudojatin
    • mkhan-twilio
    • mayberex
    • anandjha
    • pmunin
    • oscb
    • krousseau
    • brandongregoryscott
    • knksmith57
    • sachinwathore
    • fhalim-segment
    • cfree
    • mettledrum
    • 5t0k4st1k
    • maerf0x0
    • gnijor
    • ifonseka1
    • aniket.gupta
    • hjoonpm
    • lauramunozjimenez
    • celine-segment
    • parsa-segment
    • hmorgan94
    • pmcanseco-segment
    • ynguyen
    • mshwery
    • debajitr
    • masira
    • gpsamson
    • amillet89
    • cholt002
    • av-segment
    • aghotikar
    • vikrant-segment
    • ankur.agarwal
    • larryatsegment
    • lbrink
    • shivpoojan-segment
    • ariel_segment
    • zkuzmic-segment
    • scruwys1
    • sowjanyaedara
    • chrischalstrom
    • rossedfort
    • eesegment
    • lew-gordon
    • kyliepedersen
    • jinapark
    • skntwilio
    • segmentio
    • segment-admin
    • dominicbarnes
    • shobhita-agarwal
    • deanhuynh
    • jlineaweaver
    • ladanazita
    • anoonan
    • peripheral
    • achille-roussel
    • rajulvadera
    • nettofarah
    • dalchandc
    • lpediredla
    • albert.segment
    • segment-danielstjules
    • n2parko
    • segment-andy-yeo
    • sahilp
    • psankaranarayana
    • vdemedes
    • emilio-gomez-lavin
    • andreiko_ru
    • xagos
    • leifdreizler
    • alan-segment
    • tyson_segment
    • bgamwell
    • jfabre-segment
    • uditmehta
    • hellooimkat
    • brienne.mcnally
    • sanscontext
    • eculver
    • aultimus
    • salolivares
    • erikdw
    • chenxiangzhang
    • fauzyy
    • jaimal
    • davidbirdsong
    • ktrinh
    • calthomson
    • yunqiaohuang
    • dk1027
    • nielssegment
    • cdrycroft
    • yabrira
    • julee05
    • kamebkj
    • ryan_segment
    • laurenmreeder
    • tidothegreat
    • mericsson
    • prayansh-segmentt
    • stargaesser
    • andyguwc
    • jeremylarkin
    • bsneed
    • danieljackins
    • tomeliaz
    • segment-seth
    • bihl
    • shamil.ataev
    • james9446
    • priscilla.giatti
    • kellylu
    • smokeybears
    • jmbuckner
    • benhorowitz
    • yolken-segment
    • nlsun
    • thomas-pelletier-segment
    • brian-segment
    • segment-michael
    • cohara87
    • drew-thompson
    • segment-jsingh
    • vanesng
    • cvillela
    • pauljaeinyoo
    • mniehe
    • stephment
    • sharadbhadouria
    • emilyc
    • maggieyu
    • anoonan16
    • durgani
    • julio.farah
    • hblanks-segment
    • rsata
    • shyaan
    • juhaelee
    • akleiner2
    • kathryn-taylor
    • andrius-segment
    • pooyaj
    • llbsgmt
    • lab176
    • valerieernst
    • ucarion
    • solon.aguiar
    • rjenkinsseg
    • segment-ulysse
    • khinkalilover
    • maloneya
    • zackurey
    • kelcook
    • arta.razavi
    • odoren
    • alistairbarrell
    • anna.choi
    • whamo12
    • amaloney
    • gilomer
    • kiara.daswani
    • marcelopv
    • yannieyip
    • eric.rogner
    • marinhero
    • lcamposg
    • corey.ching
    • steve_at_segment
    • tepahk
    • sorrel.j
    • cjo2
    • fc-segment
    • kdharaiya
    • warrengreen
    • jon.anderson-at-segment.com
    • markzegarelli
    • stysegment
    • ajhenry
    • stacy.song
    • niveda.balananthan
    • collinvandyck
    • krlv
    • rexatsegment
    • nickaguilar
    • tri.truong
    • csayuso
    • joyce-shi
    • bradenbecker
    • neha.sanghrajka
    • reneewang
    • dan.lasky
    • sam.tapia
    • gbbastos
    • vikramkumar19
    • mpriyad25
    • peter.walker
    • jeremy.parker
    • khamidou-segment
    • smidges
    • daltonscharff