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.
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.
-
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).
-
Start tracking!
- Install the package
# npm
npm install @segment/analytics-next
# yarn
yarn add @segment/analytics-next
# pnpm
pnpm add @segment/analytics-next
- 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!')
})
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")
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) => ...);
Self Hosting or Proxying Analytics.js documentation
- 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
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>
)
- Export analytics instance.
import { AnalyticsBrowser } from '@segment/analytics-next'
export const analytics = AnalyticsBrowser.load({
writeKey: '<YOUR_WRITE_KEY>',
})
- 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>
While this package does not support web workers out of the box, there are options:
-
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.
-
Try @segment/analytics-node with
flushAt: 1
, which should work in any runtime wherefetch
is available. Warning: cloud destinations only!
-
Install npm package
@segment/analytics-next
as a dev dependency. -
Create
./typings/analytics.d.ts
// ./typings/analytics.d.ts
import type { AnalyticsSnippet } from "@segment/analytics-next";
declare global {
interface Window {
analytics: AnalyticsSnippet;
}
}
- Configure typescript to read from the custom
./typings
folder
// tsconfig.json
{
...
"compilerOptions": {
....
"typeRoots": [
"./node_modules/@types",
"./typings"
]
}
....
}
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!
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:
- Critical: Analytics Next should expect this plugin to be loaded before starting event delivery
- Non-critical: Analytics Next can start event delivery before this plugin has finished loading
and can be of five different types:
- 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.
- 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.
- Destination: Destinations to send the event to (ie. legacy destinations). Does not modify the event and failure does not halt execution.
- Enrichment: Modifies an event, failure here could halt the event pipeline.
- 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.
Feature work and bug fixes should include tests. Run all Jest tests:
$ yarn test
Lint all with ESLint:
$ yarn lint