General

Read the User’s IP address in JavaScript

A MacBook with lines of code on its screen on a busy desk

It can be quite handy for some projects to know the IP address of the client. However, this is not available in Javascript and can not be found out without external resources. Since I needed to find out the IP address of the client in Javascript for a project, I built a small solution for it and I am sharing my approach here.

The script will always return the current IP address of the client. Nothing more. Still, a function that can’t be solved client-side by default, but an external resource has to be requested.

Use cases

  • Redirect GA hits to another property based on IP, e.g. office IP
  • Do not run marketing Pixel if IP is own office
  • Create a hash of the IP to use as an ID
  • and much more..

Set up in Google Cloud as Cloud Function

(or any other Node JS environment)

Since the only logic the script needs to do is answer with the requesters IP, the code is very short. The following snippet will return the IP address in JSON format. The code can be executed by a Node.js 12 Cloud Function instance.

exports.getIp = (req, res) =>
{
	var ip = (req.headers['x-forwarded-for'] || '').split(',').pop().trim() || 
				req.connection.remoteAddress || 
				req.socket.remoteAddress || 
				req.connection.socket.remoteAddress;
	res.status(200).send('{"ip":"' + ip + '"}');
};

Working example

The following script URL and code snippets are working. Kindly use it only for testing and development purposes. Don’t use it on production. I might take it offline at any time.

Script URL

https://europe-west3-devrcc.cloudfunctions.net/whatismyip

Using with JavaScript

ajax = new XMLHttpRequest();
if(ajax!=null){
    ajax.open("GET","https://europe-west3-devrcc.cloudfunctions.net/whatismyip",true);
    ajax.onreadystatechange = function() {
        if(this.readyState == 4) {
            if(this.status == 200) {
                console.log(this.responseText);
            }
        }
    }
    ajax.send(null);
}

Using with jQuery

$.getJSON('https://europe-west3-devrcc.cloudfunctions.net/whatismyip', function(data){
  console.log(data);
})

Response

{"ip":"31.6.26.42"}

Leave a Reply