Full article

Custom URL Shortner in NodeJS

Recently I wrote an article on Ghost blog integration with a URL shortener (the dirty way). This is in sequence to it but with custom URL shortener running on my own machine. While most of this code is shared from codebyte article, I have enhanced it to serve three purposes,

  1. Authenticate using API Key
  2. Validate URL(s) or ID(s) for duplicate
  3. Response support in JSON or TXT format

At present the setup is running with the following configuration,

  1. Backend is running on port X @ IP so it has no reach from outside.
  2. NGINX webserver is running as front-end with domain xfu.io (current URL shortener). It is proxying requests to backend.

NodeJS Code:

As I mentioned the skeleton is adopted from codebyte article, I do made quick changes,

  1. Check API Key

     if (key == undefined) return res.json({success: false, msg: "No key defined."});
     if (key != "XXXXXXXXXXXXXXX" && key != "YYYYYYYYYYYYY") return res.json({success: false, msg: "Invalid key."});
     //TODO: To be checked via database
     //TODO: To be checked via separate function
  2. Check if URL or ID exists, (find URL/ID in database & list)

    • If URL exists, return the same ID & complete link: return res.json({success: true, msg: "url-exist", id: ulist[0].id, link: domain+ulist[0].id});
    • If ID exists, return error: return res.json({success: false, msg: "id-exist", url: idlist[0].url});
  3. Check requested format - JSON or TXT, and reply accordingly,

     if(type == "text") return res.send(domain+id);
     return res.json({success: true, msg: "created", id: id, link: link});

NGINX proxy-pass** site configuration,

location / {
  proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  proxy_set_header Host $http_host;
  proxy_set_header X-Forwarded-Proto $scheme;
  proxy_set_header   X-Real-IP $remote_addr;
  proxy_set_header   Host      $http_host;

And therefore, the URL shortener is running on the localhost, and my blog can access the same to generate short-links for each post. Voila!

Cheers & be safe.