• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
  • Skip to footer

Rapid Blog

  • Enterprise
  • API Hub
  • Add Your API
  • About
  • Docs
    • API Glossary
  • Blog
    • What is an API?
    • REST API Tutorials
    • Most Popular APIs
  • Sign Up
    • Log In
Blog » API Tutorials » JavaScript API Tutorials » Node.js API Tutorials » How to Build a Basic Geolocation Backend with Node/Express

How to Build a Basic Geolocation Backend with Node/Express

By Team RapidAPI // September 14, 2020

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.

Related: How to Use IP Geolocation with Python

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. 

Connect to the IPWHOIS.io API

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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
node --version
node --version
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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
mkdir geolocation-app && cd geolocation-app
npm init
npm install --save express body-parser morgan
mkdir geolocation-app && cd geolocation-app npm init npm install --save express body-parser morgan
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)

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
touch index.js
code .
touch index.js code .
touch index.js
code .

Paste the following into the index.js file:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
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}!`))
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}!`))
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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
node index.js
node index.js
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.

Connect to the IPWHOIS.io API

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

geolocation api 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.

RapidAPI Code Snippet

Connect to the IPWHOIS.io API

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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
npm install --save unirest
npm install --save unirest
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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
const unirest = require("unirest");
const unirest = require("unirest");
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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
app.get('/', (req, res) => res.send('Testing my Geolocation Node app!'))
app.get('/', (req, res) => res.send('Testing my Geolocation Node app!'))
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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
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);
});
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); });
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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
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}!`));
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}!`));
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}!`));

 

Connect to the IPWHOIS.io API

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.

RapidAPI JSON Dump

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:

  • Chrome
  • Firefox
  • Safari

Once it’s installed and enabled, return to your app and reload the page. 

RapidAPI JSON Dump Pretty

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?

Connect to the IPWHOIS.io API

5/5 - (1 vote)
« Top 8 Best Websites to Find Song Lyrics (in 2021)
How to use the API-Football API with Python »

Filed Under: JavaScript API Tutorials, Node.js API Tutorials, REST API Tutorials Tagged With: backend, express.js, geolocation, ip, ip geolocation, node.js

Team RapidAPI

Reader Interactions

Comments

  1. Todd Rosier says

    January 9, 2020 at 4:39 am

    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:)

    Reply
  2. abhuday says

    February 27, 2021 at 4:50 am

    When running this api, it shows me my singapore, which is not my correct location.

    Reply
  3. ray says

    March 25, 2021 at 1:02 pm

    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

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

Primary Sidebar

Build anything with APIs, faster.

Discover, evaluate, and integrate with any API. RapidAPI is the world’s largest API Hub with over 4 Million developers and 35,000 APIs.

Browse APIs »

APIs mentioned in this article

Connect to the IPWHOIS.io API
Connect to the IPWHOIS.io API

Footer

  • API Guides
  • API Courses
  • API Glossary
  • API Testing
  • API Management
  • Most Popular APIs
  • Free APIs List
  • How to use an API
  • Learn REST API
  • Build API’s
  • About
  • Build APIs
  • Careers
  • Contact Us
  • Write for Us
  • API Directory
  • Press Room
  • Privacy Policy
  • Terms of Use

© 2025 RapidAPI. All rights reserved.

Building an Enterprise API Program
Learn More

×