In this tutorial, you will learn how to get the current user location like country, region, city, lat, and long from the client IP address in the node js express js project.
How to Get Current Location from IP Address Node js
Steps to get current location like country, region, city, lat, and long from an IP address:
Step 1: Set up your Node.js project
First of all, You need to create a new directory for your project, and run the following command on cmd to Initialize a node js:
npm init -y
Step 2: Install required dependencies
Run the following command into it to install geo-lite package for retrieving current location information from an IP address in node js:
npm install geoip-lite
Step 3: Create the App.js
Next, open your node js project directory and create a new file called app.js
into it. Then open it in your favorite text editor. Add the following code to the file:
const geoip = require('geoip-lite');
// IP address you want to retrieve the location for
const ipAddress = '8.8.8.8';
// Get location information
const location = geoip.lookup(ipAddress);
// Print location details
console.log('IP Address:', ipAddress);
console.log('Country:', location.country);
console.log('Region:', location.region);
console.log('City:', location.city);
console.log('Latitude:', location.ll[0]);
console.log('Longitude:', location.ll[1]);
Step 4: Test Application
Run the following command to start node js application server:
node app.js
Conclusion
That’s it! You’ve successfully learned how to get current user location information from an IP address using Node.js.