Single Page Apps with Analytics.js
Analytics.js can work with your single-page applications built with technologies such as React or Vue.
If you have a single-page application and plan to use Segment a lot, you might need to add a Segment server analytics library to your build system. You can do this using Segment's analytics-node package instead of using the Analytics.js javascript code snippet. The Analytics-Node package works like any standard node-js dependency.
First add the package as a dependency:
$ npm install analytics-node
or, if you are using yarn:
$ yarn add analytics-node
Once installed, you can import analytics-node and instrument your events the same way you would with Analytics.js. The example implementation below is in React:
1import Analytics from 'analytics-node'23const analytics = new Analytics("YOUR WRITE KEY")45class ShoppingCartButton {6onPurchase = () => {7analytics.track("Item Purchased", {8itemId: "abc"9})10}1112render() {13return <button onClick={this.onPurchase}>Buy Item</button>14}1516}