ExpressJS - Guide3


What is this application about?

Express is the most popular web framework for Node, while Socket.IO is a realtime framework that enables bi-directional communication between web clients and the server. We are going to create a basic tracking pixel application using the two that has a dashboard which reports realtime visits.

Besides Express and Socket.IO we will need to install the emptygif module. When the user visits http://localhost:1337/tpx.gif, a message will be sent to all the users that are viewing the homepage. The message will contain information related to the clients, mainly their IP address and user agent.

Code for the server.js file:

var emptygif = require('emptygif');
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('')(server);

app.get('/tpx.gif', function(req, res, next) {
  io.emit('visit', {
    ip: req.ip,
    ua: req.headers['user-agent']

  emptygif.sendEmptyGif(req, res, {
    'Content-Type': 'image/gif',
    'Content-Length': emptygif.emptyGifBufferLength,
    'Cache-Control': 'public, max-age=0' // or specify expiry to make sure it will call everytime

app.use(express.static(__dirname + '/public'));


Now on the frontend all we have to do is listen for that 'visit' event emitted by the server and modify the UI accordingly, like so:

<html lang="en">
  <meta charset="UTF-8">
  <title>Realtime pixel tracking dashboard</title>
  <style type="text/css">
    .visit {
      margin: 5px 0;
      border-bottom: 1px dotted #CCC;
      padding: 5px 0;
    .ip {
      margin: 0 10px;
      border-left: 1px dotted #CCC;
      border-right: 1px dotted #CCC;
      padding: 0 5px;
  <h1>Realtime pixel tracking dashboard</h1>

  <div class="visits"></div>

  <script src=""></script>
  <script src="//"></script>
  <script src="/"></script>
    $(function() {
      var socket = io();
      var containerEl = $('.visits');

      socket.on('visit', function(visit) {
        var newItem = '<div class="visit">';
        newItem += '<span class="date">' + moment().format('MMMM Do YYYY, HH:mm:ss') + '</span>';
        newItem += '<span class="ip">' + visit.ip + '</span>';
        newItem += '<span class="ua">' + + '</span></div>';

Now start up the application, open the dashboard in a tab and the tracking pixel URL in different browsers.

See the bottom of

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License