Geolocation is the process of identifying the location of a device or person using digital information. Often, a website uses a Geolocation API to look up a user’s location by their IP address. This is useful for many things — particularly for apps that display localized search results (think Yelp for looking up restaurants near you, or Tinder for finding people to take to those restaurants.)
The RapidAPI Marketplace lists about 60 Geolocation APIs that can be used to look up a user’s location via their IP address. Today, we’ll take a look at the IPWHOIS.io API, and use it to build a very simple Node app that returns location information for a user.
In this tutorial, we’ll only be building the backend that makes the call to get the user’s Geolocation data. Once you have this data, you can pull it into any client you like – for example, you might build a React app that shows users movie data in their area.
Setting Up Node/Express
The topic of how to set up a Node/Express backend has been covered thoroughly in other tutorials, so I won’t go into too much detail about the specifics here. If you’ve never used Node or Express before, take a minute to read through this tutorial.
Ready?
Great, let’s get cracking. This tutorial will assume that you have npm, Node and Express installed. You should have at least version 10 of Node installed. To check what version of Node you are currently running, use the following command
node --version
If you’re at a lower version of Node, use nvm to install and manage a new version. Once you’re running the correct version, create a new folder for your project, initialize it as an npm project, and install Express and the required middleware
mkdir geolocation-app && cd geolocation-app npm init npm install --save express body-parser morgan
Create a server file and open it up with your favorite text editor (I’m using VS Code)
touch index.js code .
Paste the following into the index.js file:
const express = require('express') const app = express() const port = 3000 app.get('/', (req, res) => res.send('Testing my Geolocation Node app!')) app.listen(port, () => console.log(`Example app listening on port ${port}!`))
Save, and run
node index.js
And navigate to localhost:3000 in your favorite browser. You should see a screen that says “Testing my Geolocation Node app!” Not super exciting yet, but we’ve got the boilerplate for our app up and running! Let’s add the IP lookup functionality.
Using the Geolocation API
You can find the RapidAPI sandbox for the WHOIS.io IP API here. You will need to create an account and log in to be able to test the endpoint — don’t worry, it’s free! Rapid API allows you to make up to 1000 requests per day to the endpoint without incurring any fees.
Once you’ve set up an account and logged in, head to the sandbox to test the endpoint. You should see that the RapidAPI Project, X-RapidAPI-Host and X-RapidAPI-Key fields are already filled in for you. Additionally, there is an optional IP address field. If you put an IP address in this field, the API will return information for that address. If you leave it blank, the current user’s IP address will be automatically detected.
Leave the IP field blank and click “Test Endpoint.” You should get a JSON response object in the response body field on the right-hand side of the sandbox
Identifying location information redacted
It works! We can get back information about our user’s timezone, latitude and longitude, region, city, currency and more. Now we just need to add this API call to our Node app.
RapidAPI provides a handy code snippet to do this. Simply click “Code Snippet” at the top of the sandbox. Once we’re ready to add this to our Node app, we’ll copy and paste the code into our index.js file. But first, we need to do some setup.
Installing Unirest
As you can see, the RapidAPI code uses a library called Unirest to handle sending the request. We need to install this into our own app before we can use it. We can do that with npm
npm install --save unirest
If you open up your package.json file now, you should see unirest listed as a dependency.
In your index.js file, add the following on line 5
const unirest = require("unirest");
Creating the Endpoint
Our API can now use Unirest to send the request to WHOIS.io to get the user location information. Now we need an endpoint to handle the incoming request from our client. Right now, we have just one endpoint at ‘/’ – this is what gets hit when you visit the app in the browser at localhost:3000, and sends back the response of “Testing my Geolocation Node app!” We’re going to modify this endpoint to send back our geolocation data instead.
Find the following line in your index.js file
app.get('/', (req, res) => res.send('Testing my Geolocation Node app!'))
and delete the part that says res.send(‘Testing my Geolocation Node app!’). Replace it with a pair of curly braces. Instead of just sending this hardcoded string back, we’re going to add the code here to make the request to WHOIS.io, and send back the location data to the client.
Inside the curly braces, paste the following
const apiCall = unirest( "GET", "https://ip-geolocation-ipwhois-io.p.rapidapi.com/json/" ); apiCall.headers({ "x-rapidapi-host": "ip-geolocation-ipwhois-io.p.rapidapi.com", "x-rapidapi-key": "<your-api-key>" }); apiCall.end(function(result) { if (res.error) throw new Error(result.error); console.log(result.body); res.send(result.body); });
What we’ve done here is copy the code snippet from RapidAPI.com, and make a few modifications. You can see here that we are intentionally leaving out the IP address from the end of the GET request URL on line 9. This will mean that the IP address of the client will be automatically passed to WHOIS.
As you can see, I’ve left out the API key because yours will be different when you copy it from RapidAPI.
I also renamed the req variable to apiCall – this is because the function we pasted this code into already has a req object passed to it as a parameter. We don’t want to overwrite that parameter, so we rename the new request object.
Similarly, I’ve renamed the res parameter that we receive in the .end event that fires when we get a response back from WHOIS. This is for the same reason: the outer function that this code is pasted into already passes a res object, which we will need to use to send the response back to our client. We don’t want to overwrite this variable, so we need to rename it.
I also replaced the word var with const (since we’ve been using const in this tutorial so far.)
Your index.js file should now look like this
const express = require("express"); const app = express(); const port = 3000; const unirest = require("unirest"); app.get("/", (req, res) => { var apiCall = unirest("GET", "https://ip-geolocation-ipwhois-io.p.rapidapi.com/json/" ); apiCall.headers({ "x-rapidapi-host": "ip-geolocation-ipwhois-io.p.rapidapi.com", "x-rapidapi-key": "srclZqaa9imshAk9Xzz55u27oltLp1SqdiFjsnmva9PTpf2j3f" }); apiCall.end(function(result) { if (res.error) throw new Error(result.error); console.log(result.body); res.send(result.body); }); }); app.listen(port, () => console.log(`Example app listening on port ${port}!`));
Testing the App
Everything should now be in place to run our app. Because our Express setup is very basic and we don’t have any reloading capabilities or nodemon watching for our changes, we will need to stop and restart the app before we test it. Go ahead and do that by hitting ctrl + c and then running node index.js again.
Go back to the browser and refresh the page.
Identifying location information redacted
Tada! You should see a data dump of a JSON object full of the geolocation information for your user. It’s not very pretty — let’s install an extension that will make this information dump a bit easier to read. There are JSON formatting extensions available for most modern browsers. Click the link for your preferred browser and follow instructions for installation:
Once it’s installed and enabled, return to your app and reload the page.
Identifying location information redacted
Voila! you should now see a well-formatted, readable JSON object. This is purely a back end app that returns information about our user — now that you have this information, you can do whatever you like with it! Some ideas to take it from here:
- Build a simple UI with Create React App to display the information in a user-friendly way
- Send the latitude and longitude coordinates to Google Maps to get a map of the user’s current location
- Use the currency information to display prices in the user’s currency
Get creative! What would you build with this data?
Todd Rosier says
This is how I got my node js app(with express) to work:
const express = require(“express”);
const app = express();
const unirest = require(“unirest”);
app.get(“/”, (req, res) => {
var ip = req.header(‘x-forwarded-for’) || req.connection.remoteAddress;
var req2 = unirest(“GET”, “https://ip-geo-location.p.rapidapi.com/ip/” + ip);
req2.query({
“format”: “json”
});
req2.headers({
“x-rapidapi-host”: “ip-geo-location.p.rapidapi.com”,
“x-rapidapi-key”: “7a37b51785msh117405471cd8cabp1df0efjsn93704bacdc77”
});
req2.end(function (res) {
if (res.error) throw new Error(res.error);
console.log(res.body);
});
res.sendStatus(204);
});
app.listen(80, ‘192.168.1.4’);
I can get any ip from any client and check the geo location providing I use at the terminal console on my Raspbian OS: node “my .js file” > log.txt
I’am by all means not a programmer but this does the job:)
abhuday says
When running this api, it shows me my singapore, which is not my correct location.
ray says
I am also getting a location that is way off and I’ve tested with other free geolocation services online so the problem is not on my end