If you are making an app in node js or you already have an app built in node js. And in this node js app, you want to get the user’s location like country, region, city, lat, and long by client IP address.
So, in this tutorial guide, you will learn how to get the current user location from the client IP address in the node 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 in node js:
- Step 1: Set up your Node.js project
- Step 2: Install required dependencies
- Step 3: Create the App.js
- Step 4: Run this App
Step 1: Set up your Node.js project
First of all, You need to create a new directory for your project.
And then navigate to it in your terminal or cmd. And execute the following command into it to Initialize a new Node.js project:
npm init -y
Step 2: Install required dependencies
Now, you need to install geo-lite required dependencies. So, open your terminal or cmd and execute 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 = '220.127.116.11'; // 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); console.log('Longitude:', location.ll);
Step 4: Run this App
Now, open your terminal or cmd and execute the following command into it to run your node js project:
That’s it! You’ve successfully learned how to get current user location information from an IP address using Node.js.