AnalyticsUTMTrackingMiddleware.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. const _ = require('lodash')
  2. const RequestHelper = require('./RequestHelper')
  3. const AnalyticsManager = require('./AnalyticsManager')
  4. const querystring = require('querystring')
  5. const { URL } = require('url')
  6. const Settings = require('@overleaf/settings')
  7. const OError = require('@overleaf/o-error')
  8. const logger = require('@overleaf/logger')
  9. function recordUTMTags() {
  10. return function (req, res, next) {
  11. const query = req.query
  12. try {
  13. const utmValues = RequestHelper.parseUtm(query)
  14. if (utmValues) {
  15. const path = new URL(req.url, Settings.siteUrl).pathname
  16. AnalyticsManager.recordEventForSession(req.session, 'page-view', {
  17. path,
  18. ...utmValues,
  19. })
  20. const propertyValue = `${utmValues.utm_source || 'N/A'};${
  21. utmValues.utm_medium || 'N/A'
  22. };${utmValues.utm_campaign || 'N/A'};${
  23. utmValues.utm_content || utmValues.utm_term || 'N/A'
  24. }`
  25. AnalyticsManager.setUserPropertyForSessionInBackground(
  26. req.session,
  27. 'utm-tags',
  28. propertyValue
  29. )
  30. // redirect to URL without UTM query params
  31. const queryWithoutUtm = _.omit(query, RequestHelper.UTM_KEYS)
  32. const queryString =
  33. Object.keys(queryWithoutUtm).length > 0
  34. ? '?' + querystring.stringify(queryWithoutUtm)
  35. : ''
  36. return res.redirect(path + queryString)
  37. }
  38. } catch (error) {
  39. // log errors and fail silently
  40. OError.tag(error, 'failed to track UTM tags', {
  41. query,
  42. })
  43. logger.warn({ error }, error.message)
  44. }
  45. next()
  46. }
  47. }
  48. module.exports = {
  49. recordUTMTags,
  50. }