AnalyticsUTMTrackingMiddleware.mjs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import _ from 'lodash'
  2. import RequestHelper from './RequestHelper.js'
  3. import AnalyticsManager from './AnalyticsManager.js'
  4. import querystring from 'node:querystring'
  5. import { URL } from 'node:url'
  6. import Settings from '@overleaf/settings'
  7. import OError from '@overleaf/o-error'
  8. import logger from '@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. export default {
  49. recordUTMTags,
  50. }