Alexandru R
Alexandru R

Reputation: 8833

How to add campaign tracking data to any url automatically?

I get a bunch of different URL from my sources and what I would like is to redirect to the same URL, but with campaign data added to URL (to track the referred clicks).

For example I have these URLs:

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

www.example.com/id_product=5

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

And the URLs to 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 I correctly check and cover all the cases if a URL string has parameters, and add mine? I want to do it in node.js

Thank you

Upvotes: 3

Views: 2289

Answers (3)

alexandru.topliceanu
alexandru.topliceanu

Reputation: 2364

Elaborating on @snkashis, a similar but arguably more elegant solution, again using node's url module, is:

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 first looks for search and, if it can't find it, it composes the query string from the query object

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

  • search will be used in place of query

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

Upvotes: 8

snkashis
snkashis

Reputation: 2991

Here is a example showing different scenarios using Node's 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);
}

Upvotes: 2

Vadim Baryshev
Vadim Baryshev

Reputation: 26199

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

Upvotes: 0

Related Questions