Relay Google Analytics Measurement Protocol hits via Cloud Functions
Often it can be useful to use Measurement Protocol to submit events to Google Analytics from your own network, for example, when importing offline conversions.
However, if views are defined in GA containing filters to exclude your network, these events will not appear.
One solution is to use Cloud Functions to relay the submission using Measurement Protocol, such that the source of each request is no longer within your network.
-
Create a new Cloud Project
-
Navigate to Cloud Functions. Note that to use Cloud Functions, billing must be set up, however, there is a free tier, and if using the relay for offline conversions, it is likely that the cost will fall well within that. See Cloud Functions Pricing.
-
Click Create Function
-
Call the function mpRelay
-
Leave the other options as they are, ensuring the runtime is set to Node.js 6.
-
Paste in
mpRelay.js
andpackage.json
from this repository intoindex.js
andpackage.json
respectively. -
In
index.js
choose a secret key, and paste the value into theKEY
variable. This is to avoid your relay being used by others. -
Set the function to execute to
mpRelay
. -
Click Save.
-
Once the Cloud Function is set up, the UI will show an endpoint address similar to:
https://us-central1-my-project-218412.cloudfunctions.net/mpRelay
-
To send an event to GA, send a
POST
request to the above endpoint with aContent-Type
ofapplication/json
and a body structured as follows:{ "hits": [ { "v": 1, "t": "pageview", "tid": "UA-XXXXXXX-X", "cid": "123456", "dp": "%2FpageA" // etc .... }, { // Hit 2 etc... } ], "key": "YOUR_KEY_AS_PER_INDEX.JS" }
-
Note that :
- The
key
property needs to match the key specified in yourindex.js
in your Cloud Function. - The
hits
property is a list, so either single hits can be supplied, or multiple, which will use Measurement Protocol Batch Mode.
- The