Ishmam
Ishmam

Reputation: 53

How do I get user geo location from a node js(express) server?

I need to build a project to get user's country or location. With front-end user needs to give permission which could be bothersome for the API calls. Is there any way to get an approximate location of the user from their IP address in node.js(express) server?

Upvotes: 3

Views: 5428

Answers (2)

abdullah hisham
abdullah hisham

Reputation: 147

You can try this:

const express = require('express');
const geoip = require('geoip-lite');
const app = express();
const port = 3000;

app.get('/location', (req, res) => {
  const ip = req.headers['x-forwarded-for'] || req.socket.remoteAddress;
  const geo = geoip.lookup(ip);

  if (geo) {
    res.json({
      country: geo.country,
      region: geo.region,
      city: geo.city,
      ll: geo.ll
    });
  } else {
    res.status(404).json({ error: 'Location not found' });
  }
});

app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

Upvotes: 0

Agilan I
Agilan I

Reputation: 232

A solution could be to use APIs that return geoinformation for a given IP.
A sample could be this one which uses ip-api

const fetch = require('node-fetch')
const express = require('express')
const app = express()

const port = 3000

app.post('/location_specific_service', async (req, res) => {
  var fetch_res = await fetch(`https://ipapi.co/${req.ip}/json/`);
  var fetch_data = await fetch_res.json()

  res.send(`You are from ${fetch_data.region}`)
})

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})

Upvotes: 7

Related Questions