Security News
pnpm 10.0.0 Blocks Lifecycle Scripts by Default
pnpm 10 blocks lifecycle scripts by default to improve security, addressing supply chain attack risks but sparking debate over compatibility and workflow changes.
@segment/analytics-next
Advanced tools
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.
@segment/analytics-next is a JavaScript library that allows you to easily integrate Segment's analytics capabilities into your web applications. It provides a simple API to track user interactions, identify users, and manage analytics data across multiple platforms and services.
Track Events
The `track` method allows you to record any actions your users perform. This example tracks a 'Button Clicked' event with additional properties.
const analytics = require('@segment/analytics-next');
(async () => {
const [response] = await analytics.load({ writeKey: 'YOUR_WRITE_KEY' });
analytics.track('Button Clicked', {
buttonName: 'Subscribe'
});
})();
Identify Users
The `identify` method lets you associate a user with their unique ID and traits. This example identifies a user with an ID and additional traits like email and name.
const analytics = require('@segment/analytics-next');
(async () => {
const [response] = await analytics.load({ writeKey: 'YOUR_WRITE_KEY' });
analytics.identify('userId123', {
email: 'user@example.com',
name: 'John Doe'
});
})();
Page Tracking
The `page` method records page views on your website. This example tracks a page view for the 'Home Page'.
const analytics = require('@segment/analytics-next');
(async () => {
const [response] = await analytics.load({ writeKey: 'YOUR_WRITE_KEY' });
analytics.page('Home Page');
})();
Mixpanel is an advanced analytics service that helps improve web and mobile applications by tracking how users interact & engage with them. Compared to @segment/analytics-next, Mixpanel offers more advanced features for user segmentation and funnel analysis.
Amplitude is a product analytics service that helps you understand user behavior and product usage. It provides in-depth analytics and user segmentation. Compared to @segment/analytics-next, Amplitude focuses more on product analytics and user behavior insights.
Google Analytics is a widely-used web analytics service that tracks and reports website traffic. It offers comprehensive tracking and reporting features. Compared to @segment/analytics-next, Google Analytics is more focused on web traffic analysis and reporting.
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!
npm
package# npm
npm install @segment/analytics-next
# yarn
yarn add @segment/analytics-next
# pnpm
pnpm add @segment/analytics-next
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
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>
)
import { AnalyticsBrowser } from '@segment/analytics-next'
export const analytics = AnalyticsBrowser.load({
writeKey: '<YOUR_WRITE_KEY>',
})
.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 where fetch
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;
}
}
./typings
folder// tsconfig.json
{
...
"compilerOptions": {
....
"typeRoots": [
"./node_modules/@types",
"./typings"
]
}
....
}
First, clone the repo and then startup our local dev environment:
$ git clone git@github.com: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:
and can be of five different types:
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
FAQs
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 npm package @segment/analytics-next receives a total of 436,464 weekly downloads. As such, @segment/analytics-next popularity was classified as popular.
We found that @segment/analytics-next demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 290 open source maintainers collaborating on the project.
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.
Security News
pnpm 10 blocks lifecycle scripts by default to improve security, addressing supply chain attack risks but sparking debate over compatibility and workflow changes.
Product
Socket now supports uv.lock files to ensure consistent, secure dependency resolution for Python projects and enhance supply chain security.
Research
Security News
Socket researchers have discovered multiple malicious npm packages targeting Solana private keys, abusing Gmail to exfiltrate the data and drain Solana wallets.