node.jsexpressgeolocationip

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?


Solution

  • 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}`)
    })