Last active
October 3, 2019 22:58
-
-
Save DavidWells/f5497ef306723a2da353d67376c8ad95 to your computer and use it in GitHub Desktop.
Example of using analytics + a plugin (or listener) to send campaign data to a backend serverless function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Analytics from 'analytics' | |
// Listen for ?utm params and send data to Netlify function | |
const customUtmTokenPlugin = { | |
NAMESPACE: 'save-campaign-data', | |
campaign: ({ payload }) => { | |
const { campaign } = payload | |
console.log('utm data', campaign) | |
fetch('/.netlify/functions/save-campaign-data', { | |
method: 'POST', | |
headers: new Headers({ | |
'Content-Type': 'application/json' | |
}), | |
body: JSON.stringify(campaign) | |
}) | |
} | |
} | |
const analytics = Analytics({ | |
app: 'app-name', | |
plugins: [ | |
customUtmTokenPlugin, | |
// ... other plugins | |
] | |
}) | |
// OR with a listener | |
analytics.on('campaign', ({ payload }) => { | |
fetch('/.netlify/functions/save-campaign-data', { | |
method: 'POST', | |
headers: new Headers({ | |
'Content-Type': 'application/json' | |
}), | |
body: JSON.stringify(payload) | |
}) | |
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Netlify Lambda function | |
module.exports = async (event, context) => { | |
const campaignInfo = JSON.parse(event.body) | |
// Save to your DB of choice | |
return { | |
statusCode: 200, | |
body: JSON.stringify({ | |
message: 'campaign data saved successfully', | |
}), | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment