wnvko
wnvko

Reputation: 2120

Post to Google Analytics with node http

I am trying to post to Google Analytics under node with simple http request like this:

var http = require("http");
var post_options = ({
    host: "www.google-analytics.com",
    path: "/collect",
    body: "ec=a&ea=bb&ev=1&cid=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx&v=1&tid=UA-123456789-0&t=event",
    method: "POST",
    headers: {}
});
http.request(post_options, function (res) {
    console.log(res);
}).end();

but this never reaches the Google Analytics server and I cannot see it in my stats there. Using https like this does not work too:

var http = require("http");
var post_options = ({
    hostname: "www.google-analytics.com",
    port: 443,
    path: "/collect",
    body: "ec=a&ea=bb&ev=1&cid=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx&v=1&tid=UA-123456789-0&t=event",
    method: "POST",
    headers: {}
});
https.request(post_options, function (res) {
    console.log(res);
}).end();

If I try it with the request module, like this:

var request = require("request");
var path = "https://www.google-analytics.com/collect";
var options = { "body": "ec=a&ea=bb&ev=1&cid=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx&v=1&tid=UA-123456789-0&t=event", "headers": {} }
request.post(path, options, (err, httpResponse, body) => {
    console.log(httpResponse);
});

it shows in Google Analytics server immediately. Any idea what is wrong with my first approach?

Upvotes: 0

Views: 409

Answers (2)

EricF
EricF

Reputation: 61

Google Analytics 4 does not return HTTP error codes, even if an event is malformed or missing required parameters. You should test using the Google Measurement Protocol Validation Server. See: https://developers.google.com/analytics/devguides/collection/protocol/ga4/validating-events?client_type=gtag

Upvotes: 1

ralphtheninja
ralphtheninja

Reputation: 133008

The first approach uses the http core module so it will make a POST request to http://www.google-analytics.com/collect. Switch to https core module instead.

Upvotes: 2

Related Questions