Client-Side JavaScript Error Logging, Part III

I hope you enjoy this post!  To get expert ideas into how to grow your business faster online, click here.

Craig Smith  |  Founder & CEO

By Karolis Dzeja, UX Developer

This is the third part of a series of articles describing the best practices to log client-side JavaScript errors. Originally posted on my blog, read Part I and Part II.

For the server, I’ve decided to use Node.js, which will let us use JavaScript on the server-side. Node is perfectly suited for this style of application because of its lightweight, asynchronous nature.

We can immediately get our hands dirty and do some coding. Let’s check if Node is installed, if not, install Node.js.

$ node -v
v0.8.9

Then we’ll install Express, a light web framework that’ll make this a little bit easier. This will create a node_modules directory and put Express in it.

$ npm install express

Now, let’s steal Google’s pixel (because we know it does the job well) and rename it to pixel.gif.

$ wget google-analytics.com/collect
...
$ mv collect pixel.gif

Then let’s create our server, create a file app.js.

$ touch app.js

The code for the server:

// require modules
var fs = require('fs');
var express = require('express');
var app = express();

// find pixel.gif in the same directory
var pixel = fs.readFileSync(__dirname + '/pixel.gif');

// HTTP header for the pixel
var pixelHeaders = {
  'Cache-Control': 'private, no-cache, proxy-revalidate, max-age=0',
  'Content-Type': 'image/gif',
  'Content-Disposition': 'inline',
  'Content-Length': pixel.length
};

// listen for requests looking for the pixel
// and read the query string
app.get('/pixel.gif', function(request, response){
  var parameters = request.query;
  for(var key in parameters){
    console.log(key + ': ' + parameters[key]);
  }
  response.writeHead(200, pixelHeaders);
  response.end(pixel);
});

// using environmental variables for port and ip
app.listen(process.env.PORT, process.env.IP);

Save the file and start the server:

$ node app.js

Now open up your browser to wherever you are running your server and see the response:

Cannot GET /

That means the server is running. We didn’t specify what would happen if we went to /. Now change the URL to http://yourserver.com/pixel.gif?answer=42 and your browser should bring you to a 1×1 pixel (it’ll look like a blank page). But if you go back to your server’s terminal, you should see:

answer: 42

We can read the query string. Next, we’ll test our client-side script to make sure it works with this server and we’ll figure out how to store the errors in a database.

Explode Online Sales with Automation Strategies

Learn new hacks to grow conversions and maximize customer loyalty within our new eCommerce Automation Strategy Brief (PDF)

About Trinity

Helping online brands grow since 2006. How can we help you? Find out today!

Get a FREE website diagnostic consultation and report for your site.

FREE WEBINAR

B2B eCommerce Transformation