gatsby-plugin-segment-js
A lightweight & feature-rich Gatsby plugin to easily add Segment JS snippet to your site.
We need your help! 🙏🏽
We're looking for active contributors to this repo! If you're interested, simply open an issue or PR of your own and indicate that you'd like to help. Check out our open issues and PRs. We also need to beef up testing. Contributors get to:
- manage versioning and deploys by publishing new versions to NPM
- determine which features get launched by merging pull requests
- oversee the community through commenting on and managing pull requests and issues
⚜️ Being an active contributor is great for the community and your engineering resume.⚜️
Features
Packed with features:
- use multiple write keys (one for prod env, another optional one for dev)
- disable page view tracking (just in case you want to add it later manually)
- up to date (Segment snippet 4.1.0)
Install
- NPM:
$ npm install --save gatsby-plugin-segment-js
- YARN:
$ yarn add gatsby-plugin-segment-js
How to use
Setup
In your gatsby-config.js file:
plugins: [
{
resolve: `gatsby-plugin-segment-js`,
options: {
prodKey: 'SEGMENT_PRODUCTION_WRITE_KEY',
devKey: 'SEGMENT_DEV_WRITE_KEY',
trackPage: false,
trackPageDelay: 50,
host: 'https://override-segment-endpoint',
delayLoad: false,
delayLoadTime: 1000,
manualLoad: false,
customSnippet: '!function(){var analytics=window.analytics||[];...;analytics.load("${writeKey}");analytics.page();}}();'
}
}
];
Track Events
If you want to track events, you simply invoke Segment as normal in your React components — (window.analytics.track('Event Name', {...})
— and you should see the events within your Segment debugger! For example, if you wanted to track events on a click, it may look something like this:
class IndexPage extends React.Component {
...
_handleClick() {
window.analytics.track("Track Event Fired", {
userId: user.id,
gender: 'male',
age: 33,
});
}
render() {
return (
<p>
<Link onClick={this._handleClick} to="/">
Click here
</Link>{" "}
to see a track event
</p>
);
}
}
Track Pageviews
If you want to track pageviews automatically, set trackPage
to true
in your gatsby-config.js
file. What we mean by "automatically" is that whenever there is a route change, we leverage Gatsby's onRouteUpdate
API in the gatsby-browser.js
file (link) to invoke window.analytics.page()
on each route change. But if you want to pass in properties along with the pageview call (ie, it's common to see folks pass in some user or account data with each page call), then you'll have to set trackPage: false
and call it yourself in your gatsby-browser.js
file, like this:
exports.onRouteUpdate = () => {
window.analytics && window.analytics.page();
};