Search code examples
javascriptmeteorrequestiron-router

Get IP address from request object in Meteor


I want to retrieve the client's IP address before I redirect the client to an external URL.

Here is my code:

Router.route('/:_id', {name: 'urlRedirect', where: 'server'}).get(function () {
    var url = Urls.findOne(this.params._id);
    if (url) {
        var request = this.request;
        var response = this.response;
        var headers = request.headers;
        console.log(headers['user-agent']);
        this.response.writeHead(302, {
            'Location': url.url
        });
        this.response.end();
    } else {
        this.redirect('/');
    }
});

My question is: Can I get the IP address from the request object?


Solution

  • According to the Iron-Router guide, the request you get from this.request will be a typical NodeJS request object:

    Router.route('/download/:file', function () {
      // NodeJS request object
      var request = this.request;
    
      // NodeJS  response object
      var response = this.response;
    
      this.response.end('file download content\n');
    }, {where: 'server'});
    

    So you should be able to loop the IP address up in this.request.connection.remoteAddress.

    As stated in this answer, you may also have to look in this.request.headers['x-forwarded-for'] in some cases.