AnalyticsUTMTrackingMiddleware.mjs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. const host = req.headers.host
  17. const domain = host?.split('.')[0]
  18. AnalyticsManager.recordEventForSession(req.session, 'page-view', {
  19. path,
  20. ...utmValues,
  21. domain,
  22. })
  23. const propertyValue = `${utmValues.utm_source || 'N/A'};${
  24. utmValues.utm_medium || 'N/A'
  25. };${utmValues.utm_campaign || 'N/A'};${
  26. utmValues.utm_content || utmValues.utm_term || 'N/A'
  27. }`
  28. AnalyticsManager.setUserPropertyForSessionInBackground(
  29. req.session,
  30. 'utm-tags',
  31. propertyValue
  32. )
  33. // redirect to URL without UTM query params
  34. const queryWithoutUtm = _.omit(query, RequestHelper.UTM_KEYS)
  35. const queryString =
  36. Object.keys(queryWithoutUtm).length > 0
  37. ? '?' + querystring.stringify(queryWithoutUtm)
  38. : ''
  39. return res.redirect(path + queryString)
  40. }
  41. } catch (error) {
  42. // log errors and fail silently
  43. OError.tag(error, 'failed to track UTM tags', {
  44. query,
  45. })
  46. logger.warn({ error }, error.message)
  47. }
  48. next()
  49. }
  50. }
  51. export default {
  52. recordUTMTags,
  53. }