Home > OS >  How to get the client's country in express Js?
How to get the client's country in express Js?

Time:12-12

How to get the client's correct country name or phone code in express JS?

CodePudding user response:

You can try to get the requesting country by the IP. Have a look at the NPM package geoip-lite. Actually, there are quite a few similar packages like this.

Here is an example of the implementation

const express = require('express');
const app = express();
const { lookup } = require('geoip-lite');
const router = express.Router();

router.get('/someroute', (req,res) => {
  const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
  console.log(ip); // ip address of the user
  console.log(lookup(ip)); // location of the user
});

app.use('/', router);
app.listen(5000);

The result of console.log(lookup(ip)); will look like

{ range: [ 3479298048, 3479300095 ],
  country: 'US',
  region: 'TX',
  eu: '0',
  timezone: 'America/Chicago',
  city: 'San Antonio',
  ll: [ 29.4969, -98.4032 ],
  metro: 641,
  area: 1000 }

IMPORTANT: Coordinates may be the approximate location of the operator and not a specific device

CodePudding user response:

You can ask the user (in their server-side profile) and then remember that associate that with their login .

Or you can use the IP address that is reported as belong to the client and use some server-based libraries to try to guess what country and zipcode the user is in. This works sometimes and doesn't work other times so it's really just a guess.

Things like VPNs will totally confuse this IP lookup because the IP address you'll be looking us is the VPN's host IP, not the actual client IP (which is hidden from your server). For example, if you were a business user traveling in Italy and using a corporate VPN from your company ion Britain, the IP lookup would think you were in Britain.

And, if the real client IP address is actually available, then zipcode or areacode lookups are often only approximate as it really depends upon how the user's ISP deploys their public IP addresses. I've noticed that many services can tell I'm in the northern part of my state, but are way off on which actual zipcode I'm in.

  • Related