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"}

Get the location based on the IP

If you want to get the location based on the user’s IP address, you need to request a geo-location IP database, such as ipinfo.io. Services like this can give you a location in an API response like this one:

{
    "ip": "54.246.228.58",
    "hostname": "ec2-54-246-228-58.eu-west-1.compute.amazonaws.com",
    "city": "Dublin",
    "region": "Leinster",
    "country": "IE",
    "loc": "53.3331,-6.2489",
    "org": "AS16509 Amazon.com, Inc.",
    "postal": "D02",
    "timezone": "Europe/Dublin"
}

4 Comments Add New Comment

  1. Note Info says:

    this is work for me
    //////////////////////////////////////////////////////////////
    // Ditect user info
    let Url = “https://www.cloudflare.com/cdn-cgi/trace”;
    let AjaxUrl = new XMLHttpRequest();
    AjaxUrl.open(“get”, Url);
    AjaxUrl.send();

    AjaxUrl.onreadystatechange = function () {
    if (AjaxUrl.readyState === 4 && AjaxUrl.status === 200) {
    let resultUrl = AjaxUrl.responseText;

    let mapUrlStart = resultUrl.indexOf(“ip”) + 3;
    let mapUrlEnd = resultUrl.indexOf(“ts”);
    let IpResult = resultUrl.slice(mapUrlStart, mapUrlEnd);
    localStorage.setItem(“Ip”, IpResult);

    //console.log(resultUrl);

    }
    };

    console.log(localStorage.getItem(“Ip”))

    1. Thomas says:

      Hi Tamsin, if you want to get the location, you need to use this IP address and process it by a geo-location service like ipinfo.io. With that, you will get the location of the IP address. A response from their API could look like this:
      {
      "ip": "54.246.228.58",
      "hostname": "ec2-54-246-228-58.eu-west-1.compute.amazonaws.com",
      "city": "Dublin",
      "region": "Leinster",
      "country": "IE",
      "loc": "53.3331,-6.2489",
      "org": "AS16509 Amazon.com, Inc.",
      "postal": "D02",
      "timezone": "Europe/Dublin"
      }

Leave a Reply