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

Using with JavaScript

ajax = new XMLHttpRequest();
    ajax.onreadystatechange = function() {
        if(this.readyState == 4) {
            if(this.status == 200) {

Using with jQuery

$.getJSON('', function(data){



2 Comments Add New Comment

  1. Note Info says:

    this is work for me
    // Ditect user info
    let Url = “”;
    let AjaxUrl = new XMLHttpRequest();“get”, Url);

    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);




Leave a Reply