How do I automatically add campaign tracking data to any URL?

I am getting a bunch of different urls from my sources and I would like to redirect to the same url but with campaign data appended to the url (to track specified clicks).

For example, I have these urls:

www.example.com/category/product/name.html

www.example.com/id_product=5

I want to add the following at the end: utm_source = SOURCE & utm_medium = MEDIUM & utm_campaign = CAMPAIGN

And the urls will become

www.example.com/category/product/name.html?utm_source=SOURCE&utm_medium=MEDIUM&utm_campaign=CAMPAIGN

www.example.com/id_product=5&utm_source=SOURCE&utm_medium=MEDIUM&utm_campaign=CAMPAIGN

How to properly check and cover all cases if the url string contains parameters and add mine? I want to do this in node.js

thank

+3


source to share


3 answers


While developing @snkashis, a similar but possibly more elegant solution, again using the url node module:

var addQueryParams = function (cleanUrl) {
  var obj = url.parse(cleanUrl, true, false);   
  obj.query['utm_source'] = 'SOURCE';
  obj.query['utm_medium'] = 'MEDIUM';
  obj.query['utm_campaign'] = 'CAMPAIGN';
  delete obj.search; // this makes format compose the search string out of the query object
  var trackedUrl = url.format(obj);
  return trackedUrl;
};

      



This works because url.format looks first search

and if it can't find it, it composes a query string from an objectquery

(taken from node url module documentation http://nodejs.org/api/url.html#url_url_format_urlobj )

  • search will be used instead of query

  • query (object; see querystring) will only be used if there is no search.

+8


source


Here's an example showing different scenarios using the Node URL module.



var url = require('url');

var exurls = ["www.example.com/category/product/name.html","www.example.com/id_product=5?hasparam=yes"]

var to_append = "utm_source=SOURCE&utm_medium=MEDIUM&utm_campaign=CAMPAIGN";

for (i=0;i<exurls.length;i++) {
    var parsedobj = url.parse(exurls[i],true,false);
    //Below checks if param obj is empty.
    if (Object.keys(parsedobj.query).length!==0) {
        var newpath = parsedobj.href+"&"+to_append;
    }
    else {
        var newpath = parsedobj.href+"?"+to_append;
    }
    console.log(newpath);
}

      

+2


source


Connect will help you:

var connect = require('connect');

var app = connect();
app.use(connect.query());
app.use(function (req, res, next) {
    console.log(req.query);
    res.end(JSON.stringify(req.query));
});

app.listen(3000);

      

0


source







All Articles