Url utm tracking tokens are very commonly used for measuring the effectiveness of marketing campaigns. They are very useful when running ads, sending emails, and tracking traffic from external sources. For more on what utm token are checkout this post.
When using google analytics, these utm tokens are automatically saved into google analytics. Yay 🎉
But, what if we want to save the campaign data in other tools? Or what if we aren't using google analytics at all and want to collect these metrics?
We can use the analytics
npm package to do this!
The campaign
event
In the analytics lifecycle, there is a campaign event that is emitted if there are utm
parameters found in the current URL.
This campaign event can be hooked into with a plugin or a listener.
Using a custom plugin
- Create a custom plugin
- Attach the plugin to analytics when it's initialized
import Analytics from 'analytics'
/* 1. Create the plugin & functionality you want to trigger */
const customPlugin = {
// All plugins have a NAMESPACE
NAMESPACE: 'save-campaign-data',
// Attach a function to the 'campaign' event
campaign: ({ payload }) => {
console.log('utm data', payload.campaign)
// Send data elsewhere, save to localStorage etc.
}
}
/* 2. Attach the plugin to the plugins array when you initialize analytics */
const analytics = Analytics({
app: 'app-name',
plugins: [
customPlugin,
// ... other plugins
]
})
After attaching the plugin, anytime there is a utm
paramters in a url this functionality will trigger.
For example:
?utm_source=a&utm_medium=b&utm_term=c&utm_content=d&utm_campaign=e
Will fire the campaign
event with the payload
const customPlugin = {
NAMESPACE: 'save-campaign-data',
campaign: ({ payload }) => {
console.log('utm data', payload.campaign)
/*{
source: 'a',
medium 'b',
term: 'c',
content 'd',
name: 'e'
}*/
}
}
Using a Listener
You can also react to the campaign
event via a listener anywhere in your application code.
- Initialize analytics
- Set a listener with
on
oronce
to listen for thecampaign
event
import Analytics from 'analytics'
const analytics = Analytics({
app: 'app-name',
plugins: [
// ... other plugins
]
})
/* Attach a listener to campaign */
analytics.on('campaign', ({ payload }) => {
console.log('utm data', payload.campaign)
// Send data elsewhere, save to localStorage etc.
})
You can also use the once
listener to ensure a callback is only fired once.
/* Alternatively Attach a listener to campaign */
analytics.once('campaign', ({ payload }) => {
console.log('utm data', payload.campaign)
// Send data elsewhere, save to localStorage etc.
})
For more information on how to use the analytics library for page tracking, custom events, & identifying visitors. See the docs!
Top comments (1)
Thank you for your article, very practical!
For those of you who don't know what a Google UTM is or who are wondering what it's all about, I wrote a little article about it : UTM Google, all you need to know to use them better!
Thanks all !