Allow access to directory only from specific IP addresses in node.js

I have a simple socket.io app and I want to protect directory which is emitting events to other connected sockets.

var io = require('socket.io'),
        connect = require('connect');

var app = connect().use(connect.static('public')).listen(3000);
var children = io.listen(app);

Inside public directory I have all files that users can access. Inside public/_app I have an app that is emitting events to other connected sockets. This directory should be accessible only from my IP address.

Thanks.

You can insert a custom middleware before you insert the static middleware:

var app = connect()
          .use(function(req, res, next) {
            if (req.url.indexOf('/_app/') === 0) // YOUR 'HIDDEN' PATH
            {
              var ipnumber = req.socket.address().address;
              if (ipnumber !== '127.0.0.1')     // YOUR IP NUMBER 
              {
                res.writeHead(404);
                return res.end();
              }
            }
            next();
          })
          .use(connect.static('public'))
          .listen(3000);

This generated a 404 Not Found response when an invalid IP number is trying to access your administration app. You could generate a 401 Unauthorized instead, of course.