Is it possible to find device geo location based on ip address using NodeJS?

I'm trying to implement a feature such as the one given by Instagram; I'm talking about its "login activity" page. This is what I'm talking about: enter image description here

Every time the user logs in, the device being in used is currently stored in the page. How would I go about that?

The current code that I have uses two libraries, one to find the ip.address() from the device being used and a second one that is supposed to help me to fetch the location data concerning the given ip address. Sadly, I'm unable to make it work. This is what the code looks like:

const ipLocation = require('ip-to-location')
const ip = require('ip')

const loc = await ipLocation.fetch(ip.address())
console.dir('Location', loc)
await User.findOneAndUpdate(
  { email: req.body.email },
  {
    $push: {
      loginActivity: {
        type: 'Point',
        coordinates: [loc.longitude, loc.latitude],
        // formattedAddress: loc[0].formattedAddress,
        // street: loc[0].streetName,
        city: loc.city.city,
        state: loc.region_name,
        zipcode: loc.zip_code,
        country: loc.country_code,
      },
    },
  }
)

Is there any alternate library to use? or can someone point me in the right direction to make this possible?


Solution 1:

Well, if you can get the ip address of an user, you can try ipgeolocation.io

This is a free api that can give you latitude and longitude value of an ip address (and much more if you need).

More at documentation