Skip to content

Instantly share code, notes, and snippets.

@zcourts
Created September 8, 2020 08:58
Show Gist options
  • Save zcourts/0e2d7e72931b77835dcc1e6ee77fd82c to your computer and use it in GitHub Desktop.
Save zcourts/0e2d7e72931b77835dcc1e6ee77fd82c to your computer and use it in GitHub Desktop.

By using the measurement protocol events can be sent to GA with any HTTP client (brower or server side).

curl 'https://www.google-analytics.com/collect' \
  -H 'user-agent: switch-server' \
  --data-raw 'v=1&t=event&tid=UA-XXXXXXXX-Y&cid=cid3&ec=upgrade&ea=start_trial&el=Start%20trial&ev=1' \
  --compressed

Note: user-agent is required. OR

fetch("https://www.google-analytics.com/collect", {
  "headers": {
    "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
  },
  "body": "v=1&t=event&tid=UA-XXXXXXXX-Y&cid=cid3&ec=upgrade&ea=start_trial&el=Start%20trial&ev=1",
  "method": "POST",
  "mode": "cors",
  "credentials": "omit"
});

Replace upgrade with your own event category and start_trial with your own event action and Start trial with your own event label.

Use https://ga-dev-tools.appspot.com/hit-builder/ to generate the event. The fields available are documented at https://developers.google.com/analytics/devguides/collection/protocol/v1/devguide The reference at https://developers.google.com/analytics/devguides/collection/protocol/v1/reference mentions that user agent is required.

I got to these via https://stackoverflow.com/a/9509684/400048 and https://stackoverflow.com/a/32313490/400048

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment