Press enter to see results or esc to cancel.

GET VISITOR’S IP ADDRESS IN JAVASCRIPT

HOW TO OBTAIN USER IP ADDRESS IN JAVASCRIPT?

We will learn 3 different ways to obtain visitor’s IP address:-

  1. CLIENT SIDE JAVASCRIPT + READY-MADE APIs
  2. CLIENT JS + NODEJS
  3. CLIENTJS + PHP

You must’ve noticed that all three sections which I have mentioned above require some kind of API or backend, this is because we cannot obtain IP address with just javascript in the browser, we need some server-side work however if you do not have experience on server-side you do not need to worry follow the first way where you will use ready-made API so you won’t have to write backend since it is already written by the ready-made API’s company

CLIENT JS + READY-MADE APIs:

There are a lot of ready-made API services, but we will be using ipinfo.io,

WHY ARE WE USING IPINFO.IO?

We are using ipinfo.io because it allows us 50,000 Request per Month for free, which is a huge quota and I couldn’t find any other API having this huge limit for free. however, you can upgrade your plan according to your needs.

Creating an account on IPINFO.io is optional but preferred, you’ll get a token when you create an account, You can read IPINFO.IO’s Documentation for a deep understanding

CLIENT CODE SAMPLE:

let apiURL= 'https://ipinfo.io/json'

const getIP=async()=>{
  
   let IPData= await fetch(apiURL).then(j=>j.json()) 
   console.log(IPData)
   // {ip: "167.99.230.64", city: "North Bergen",  …}
}

you don’t need to read further, this is it you got the IP address and Geographical details of the IP, but if you need more limit than 50K request per month you’ll probably need to write and host your own API if that’s the case, you can follow the other 2 sections below

CLIENT JS + NodeJS:

Now in this method we will be using two technologies, Javascript on the browser and Javascript on the server (NodeJS), For this you need a hosting service where you can host your NodeJS server, However, this is not a hosting tutorial so I won’t go deep about hosting NodeJS, but I can suggest Heroku as it is the best free NodeJS host at the moment.

NODEJS CODE SAMPLE:

const cors = require('cors');
const express = require('express')
const app = express()
const port = process.env.PORT||3000

var corsOptions = {
    origin: '*', //everyone is allowed, You can write your domain here so only you can get the response from this server.
    optionsSuccessStatus: 200, // For legacy browser support
    methods: "GET"
}

app.use(cors(corsOptions))
app.get('/', (req, res) => {

    let IP = (req.headers['x-forwarded-for'] ||'').split(',').pop().trim() ||
        req.connection.remoteAddress ||
        req.socket.remoteAddress ||
        req.connection.socket.remoteAddress ||
        req.headers['x-appengine-user-ip'] ||
        req.headers['fastly-client-ip'] ;


        res.send(IP)
})


app.listen(port, () => console.log(`go to ==>>> http://localhost:${port}/`))

So here let me explain this code, We are using express to create a server in nodeJS this will allow us to listen to HTTPS requests, such as a GET request so that we can return IP address in response.

In NodeJS normally we get IP address using the request header x-forwarded-for as mentioned in code: req.headers['x-forwarded-for'] but the header name depends on your hosting configuration, such as if the IP address is coming from a remote address we will get the IP address using `req.connection.remoteAddress`
For example:

'x-forwarded-for' will not work on firebase cloud hosting it will return undefined or null, so we will use ‘fastly-client-ip‘ to get an IP address in firebase hosting, So the headers are dependent on which hosting you are using and It’s configuration that is why I have added all the headers and ways with OR operator so whatever the header works for your server will assign an IP address to the variable.
Now here we are also splitting 'x-forwarded-for' because on some hostings it returns more than one IP address separated with a comma.

GEO-IP DATA?

The above method returns just the IP address, No information about the country or location of IP address which may be required in some cases, Now we create another endpoint where we will return an object with IP and all related information, To get the country and other information of IP address we need a database having GEOGRAPHICAL IP ADDRESS details,

In-short we will use a third-party library to extract GEOGRAPHICAL data of the IP address, There are many libraries available but we will use GeoIP-Lite as this is the most downloaded library in this category.

NODEJS CODE SAMPLE WITH GEOIP

const geoIP = require('geoip-lite');
const cors = require('cors');
const express = require('express')
const app = express()
const port = process.env.PORT||3000

const getIP = (req) => (
    (req.headers['x-forwarded-for'] || '').split(',').pop().trim() ||
    req.connection.remoteAddress ||
    req.socket.remoteAddress ||
    req.connection.socket.remoteAddress ||
    req.headers['x-appengine-user-ip'] ||
    req.headers['fastly-client-ip']
)
var corsOptions = {
    origin: '*', //everyone is allowed, You can write your domain here so only you can get the response from this server.
    optionsSuccessStatus: 200, // For legacy browser support
    methods: "GET"
}

app.use(cors(corsOptions))
app.get('/', (req, res) => res.send(getIP(req)))

app.get('/IPwithData', (req, res) => {
  
    let IP = getIP(req);
    let geo = geoip.lookup(IP);
    let notFound = IP == "::1" || IP == null || IP == undefined

    res.json({ ip: IP, ...geo, ...notFound ? { error: "An error occurred, IP address not found" } : {} })
})

app.listen(port, () => console.log(`go to ==>>> http://localhost:${port}/`))

Here we created another endpoint name “IPwithData” and in response, we are sending the data received from third-party API “GeoIP-Lite” as it will look up into it’s database for details related to the IP address and returns all the details as an object.

Please note that the IP address is not found when you run this project locally on your machine, Nodejs will return “::1” as your IP address, but it will work perfectly when you host it on a Nodejs server like heroku.

Now we are done with the NodeJS/Serverside part of our “CLIENT JS+ NODEJS” section, let’s move toward the client-side code of this section

CLIENT SIDE CODE SAMPLE

let apiURL= 'https://ip-address-js.herokuapp.com/' //my heroku server url.
let apiURLfull= 'https://ip-address-js.herokuapp.com/IPwithData'

const getIP=async()=>{
  
   let IP= await fetch(apiURL).then(t=>t.text()) 
    console.log(IP) // 445.142.8.9 => String
    
   let IPData= await fetch(apiURLfull).then(j=>j.json()) 
    console.log(IPData)
     /*  => Object
     ***************
         { ip: "445.142.8.9"
           range: [ 3479298048, 3479300095 ],
           country: 'US',
           region: 'TX',
           eu: '0',
           timezone: 'America/Chicago',
           city: 'San Antonio',
           ll: [ 29.4969, -98.4032 ],
           metro: 641,
           area: 1000 
        }
     ****************
     */
}

client-side code of this section is almost the same compared to the code of the “CLIENTJS+ READY-MADE API” section.

Now here in this clientJS sample, the apiURL variable contains the URL of my Heroku server where I deployed the nodeJS code.

CLIENT JS + PHP

Now ClientJS+PHP is almost similar to NodeJS section, The only difference is that we write the backend code in PHP.

PHP CODE SAMPLE

<?php
  header("Access-Control-Allow-Origin: *");//Allow request from all domains.

//whether ip is from share internet
if (!empty($_SERVER['HTTP_CLIENT_IP']))   
  {
    $ip_address = $_SERVER['HTTP_CLIENT_IP'];
  }
//whether ip is from proxy
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))  
  {
    $ip_address = $_SERVER['HTTP_X_FORWARDED_FOR'];
  }
//whether ip is from remote address
else
  {
    $ip_address = $_SERVER['REMOTE_ADDR'];
  }
echo $ip_address;
?>

Now this will return IP address string, but in-some cases you need Geographical data of IP address so we will use the same database that we used in NodeJS, MaxMind’s GeoIP-Lite2.

PHP CODE SAMPLE WITH GEOIP

<?php
  header("Access-Control-Allow-Origin: *");//Allow request from all domains.


//* Grab the latest geoip2.phar: https://github.com/maxmind/GeoIP2-php/releases
require_once("geoip2.phar");
use GeoIp2\Database\Reader;

if (!empty($_SERVER['HTTP_CLIENT_IP']))   
  {
    $ip_address = $_SERVER['HTTP_CLIENT_IP'];
  }
//whether ip is from proxy
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))  
  {
    $ip_address = $_SERVER['HTTP_X_FORWARDED_FOR'];
  }
//whether ip is from remote address
else
  {
    $ip_address = $_SERVER['REMOTE_ADDR'];
  }

// * Grab the latest GeoIP2 Lite Database(s): https://dev.maxmind.com/geoip/geoip2/geolite2/
// City DB
$readCity = new Reader('GeoLite2-City.mmdb');  
$record = $readCity->city($ip_address);
$myObj->ip =$ip_address;
$myObj->country =$record->country->name ;
$myObj->countryCode = $record->country->isoCode;
$myObj->city =$record->city->name;
$myObj->region =$record->mostSpecificSubdivision->name;
$myObj->regionCode =$record->mostSpecificSubdivision->isoCode;
$myObj->loc->lat =$record->location->latitude;
$myObj->loc->lng =$record->location->longitude;


echo json_encode($myObj);

Now our PHP API/Backend for IP address with GeoIP data is complete, let’s move forward to the client-side JS code to fetch these details on javascript.

CLIENT JS CODE SAMPLE

let apiURL= 'https://KashanHaider.com/IP/' //my php file url.
let apiURLfull= `${apiURL}Data/`

const getIP=async()=>{
  
   let IP= await fetch(apiURL).then(t=>t.text()) 
    console.log(IP) // 445.142.8.9 => String
    
   let IPData= await fetch(apiURLfull).then(j=>j.json()) 
    console.log(IPData)
     /*  => Object
     ***************
        {    
           ip: "445.142.8.9",
           city: "Islamabad",
           country: "Pakistan",
           countryCode: "PK",
           loc: {lat: 24.9056, lng: 67.0822},
           region: "Sindh", //Can be null in some countries.
           regionCode: "SD" //Can be null in some countries.
        } 
     ****************
     */
}

Wohooo!…

You’ve learnt all three ways of obtaining IP address in Javascript, If you’ve come this far and you believe that this blog helped you make sure to share the knowledge by sharing this blog.

F.A.Q:

WHAT IS AN IP ADDRESS?

An IP address can be compared to a Phone number, everyone has their phone number and it is a unique number so that you know where the call/message is coming from, Similarly, IP Address is completely unique to the computer or user it is assigned to. The creation of these numbers allows routers to identify where they are sending information on the internet.

WHY DO WE OBTAIN IP ADDRESS?

Well if you’re reading this page it means you already have a use-case but still, I will give you a few example,

  1. Google Analytics tool it uses IP address to differentiate unique visitors.
  2. Netflix uses the IP Address to detect the country of user and then display top trending movies of user’s country.
  3. you can use an IP address to block a user from your website,
  4. you can even block a whole country using the IP address,
  5. You can monitor your customer’s behavior and track your customers to increase your sales/orders and many more.

After reading these example, Now you know how powerful the IP address is.

Please note that some countries require user’s consent before obtaining any unique information from users, such as IP address so make sure to do some research on this.

WHAT IS CLIENT JS?

CLIENT JS full form Client-Side Javascript means the javascript that process on client-side in the browser

WHAT IS READY-MADE API?

READY-MADE APIs means a service/website that provides a ready-made endpoint, when a request is made to this endpoint you get the IP address in response

Have more questions? write down in the comment section.

More Articles:

0

SELECT
LANGUAGE

Send this to a friend