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:

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

And the urls will become

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



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; // 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 )

  • search will be used instead of query

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



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

var url = require('url');

var exurls = ["",""]

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;




Connect will help you:

var connect = require('connect');

var app = connect();
app.use(function (req, res, next) {





All Articles