
Let’s face it, knowing where your users are coming from can be a total game-changer for your web app. Maybe you need to serve up region-specific content, display prices in local currencies, or flag suspicious logins from unexpected locations. Whatever your use case may be, implementing geolocation data unlocks a ton of possibilities for customization, security and user experience.
In this guide, I’ll walk you through building an app that leverages IPstack’s geolocation API to transform ordinary IP addresses into rich geolocation data. We’ll start with the basics of IP address API integration and work our way up to a fully functional app that can detect and display location info in real time using JavaScript. By the end, you’ll have the skills to implement IP geolocation features that can seriously level up your user experience.
The best part? You don’t need to be a geo-data expert to pull this off. Let’s dive into the world of IP location APIs.
Table of Contents
Key Takeaways
- IPstack offers a straightforward REST API for IP-to-location mapping
- The IP geolocation API lets you look up IPs individually or in bulk
- Implementation requires just a few lines of code but gives you tons of location data along with security, connections, and routing type information.
- The geolocation IP API free tier gives you 100 monthly requests (perfect for testing your implementation)
- The IP address API returns everything from coordinates to timezone, language, and currency info
- You can build a slick location visualizer with minimal effort
Understanding the IPstack API
What is IPstack?
IPstack is a REST API that does one thing really well: it converts IP addresses into detailed location data. You pass it an IP, and it tells you the country, region, city, postal code, and a bunch of other useful geolocation information. The IP location API also throws in bonus data like timezone info, currency details, and even security threat assessments if you’re on a premium plan.
It’s a huge time-saver compared to maintaining your own geolocation database (which would be a nightmare to keep updated). Whether you’re developing web applications, mobile apps, or backend services, IPstack’s IP address API provides reliable geolocation data with minimal integration effort.
API Endpoints
The API gives you three main endpoints to work with:
Standard Lookup – For checking a single IP:
https://api.ipstack.com/134.201.250.155?access_key=ACCESS_KEY
Bulk Lookup – For checking multiple IPs in one go:
https://api.ipstack.com/134.201.250.155,72.229.28.185?access_key=ACCESS_KEY
Requester Lookup – For checking the IP of whoever is making the request:
https://api.ipstack.com/check?access_key=ACCESS_KEY
Response Format
When you send a request to the API, you’ll get back a JSON object (or XML if you prefer) packed with location data. Here’s what a typical response looks like:
{
"ip": "134.201.250.155",
"type": "ipv4",
"continent_code": "NA",
"continent_name": "North America",
"country_code": "US",
"country_name": "United States",
"region_code": "CA",
"region_name": "California",
"city": "Los Angeles",
"zip": "90013",
"latitude": 34.0655,
"longitude": -118.2405,
"location": {
"geoname_id": 5368361,
"capital": "Washington D.C.",
"languages": [
{
"code": "en",
"name": "English",
"native": "English"
}
],
"country_flag": "https://assets.ipstack.com/images/assets/flags_svg/us.svg",
"country_flag_emoji": "🇺🇸",
"calling_code": "1",
"is_eu": false
},
"time_zone": {
"id": "America/Los_Angeles",
"current_time": "2018-03-29T07:35:08-07:00",
"gmt_offset": -25200,
"code": "PDT",
"is_daylight_saving": true
},
"currency": {
"code": "USD",
"name": "US Dollar",
"symbol": "$"
},
"connection": {
"asn": 25876,
"isp": "Los Angeles Department of Water & Power"
}
}
Pretty sweet, right? You get everything from basic country info to exact coordinates, timezone data, and even ISP details all from a single API call.
Getting Started with IPstack
Setting Up Your Account

Before we write any code, you’ll need to grab an API key:
- Head over to IPstack’s signup page
- Register for a free account (you get 100 monthly requests, which is plenty for testing & development)
- Once you’re in, you’ll get your API access key
Hold onto that key, we’ll need it for all our geolocation API calls.
Making Your First API Request
First, make sure you have Node.js Installed, if you don’t follow this tutorial!
Let’s create a simple script to test out the IP geolocation API. First, set up a new project folder and create a file called first-request.js in your code editor.
Now open first-request.js in your favourite code editor and add the following code to make a simple request to the IPstack API:
The script will make a basic request to the IPstack endpoint with an example IP address and your access key, then log the geolocation data to the console.
// You'll need node-fetch for Node.js versions before 18
// If you're on Node.js 18+, you can use the native fetch API instead
const fetch = require('node-fetch');
// Replace this with your actual API key from IPstack
const accessKey = 'ACCESS_KEY';
const ipAddress = '134.201.250.155'; // Let's use an example IP
// Make the API request
fetch(`https://api.ipstack.com/${ipAddress}?access_key=${accessKey}`)
.then(response => response.json())
.then(data => {
//print the JSON
console.log('Geolocation data:');
console.log(JSON.stringify(data, null, 2));
})
.catch(error => console.error('Error:', error));
Now you can try running the script you just made by typing the following into your console
# If you're on Node.js < 18, install node-fetch first
npm install node-fetch@2
# Run the script
node first-request.js
If everything works, you should see a blob of JSON in your terminal with all the location details for that IP address. That’s your geolocation data goldmine right there!
Building a Simple IP Lookup Tool
Now that we have the basics down, let’s build something a bit more useful! a CLI (Command Line Interface) tool that lets you look up any IP address from the command line. When we run this file in the command prompt we will give it an IP address as a parameter and it will give us information nicely formatted in the console.
Let’s start by creating a new file in your code editor, and name it ip-lookup.js
Our script will include functionality to:
- Take an IP address as a command-line argument
- Make an API call to IPstack’s geolocation API
- Format and display the location data in a user-friendly way
- Handle both specified IPs and the user’s own IP address
Now this file will look something like this:
const fetch = require('node-fetch'); // If you're using Node.js < 18
// If you're on Node.js 18+, you can use the built-in fetch API
const accessKey = 'ACCESS_KEY';
// Our IPstack API call
async function lookupIP(ipAddress) {
try {
const response = await fetch(
`https://api.ipstack.com/${ipAddress}?access_key=${accessKey}`
);
const data = await response.json();
if (data.success === false) {
console.error('Error:', data.error.info);
return;
}
// Let's format this nicely for the console
console.log('\n📍 IP LOCATION DETAILS 📍\n');
console.log(`IP: ${data.ip}`);
console.log(`Type: ${data.type}`);
console.log(`Location: ${data.city}, ${data.region_name}, ${data.country_name}`);
console.log(`Coordinates: ${data.latitude}, ${data.longitude}`);
if (data.time_zone) {
console.log(`Timezone: ${data.time_zone.id} (${data.time_zone.current_time})`);
}
if (data.currency) {
console.log(`Currency: ${data.currency.name} (${data.currency.symbol})`);
}
if (data.connection) {
console.log(`ISP: ${data.connection.isp}`);
}
} catch (error) {
console.error('Failed to fetch IP data:', error);
}
}
if (process.argv.length > 2) { // If you run this with an argument, it'll look up that IP
lookupIP(process.argv[2]);
} else {
lookupIP('check'); // Otherwise, it'll look up the requester's IP
}
To use our IP lookup API, we can run it by typing the following commands in the command line to either check a specific IP address or look up your own IP.
node ip-lookup.js 999.999.999.999 # put the desired IP after the file name
# or
node ip-lookup.js # Look up your own IP
Creating a Real-Time Visitor Tracker
Now let’s build something a lot better, something that’s resume-worthy if you’re still having trouble looking for that job in big tech! A web app that tracks and visualizes visitor locations on a map in real time using the IP geolocation API. We’ll use Node.js with Express for the backend and basic HTML/JS with Leaflet for the map.
Setting up Your Geolocation API Backend
First, let’s set up our server. Create a directory for your project and initialize it with npm, then install the necessary dependencies by running these in your command line:
mkdir project_folder_name
npm init -y
npm install express node-fetch@2 # Use node-fetch@2 for Node.js < 18
Now, let’s create a server.js file in our directory. At the start of this file, we want to declare the constants needed to set the server up, configure express to serve static files, and create API endpoints that our frontend will use to get geolocation data.
Our backend will provide these key functionalities:
- An endpoint to look up geolocation data for a specific IP address
- An endpoint to retrieve the visitor’s own IP address
- Serving the frontend HTML/CSS/JS files
const express = require('express');
const fetch = require('node-fetch');
const path = require('path');
const app = express();
const PORT = process.env.PORT || 3000;
const ACCESS_KEY = 'ACCESS_KEY';
After we want the app to use static files from a subfolder we will make where we will store our index.html and other app files.
// Serve static files from the 'public' directory
app.use(express.static(path.join(__dirname, 'public')));
Next, we’re going to want to add the endpoints to our server that will be called from our front end and have our app listen for these endpoint calls.
// Endpoint to get geolocation data for an IP
app.get('/api/geolocation/:ip', async (req, res) => {
const ip = req.params.ip === 'myip' ? 'check' : req.params.ip;
try {
const response = await fetch(
`https://api.ipstack.com/${ip}?access_key=${ACCESS_KEY}`
);
const data = await response.json();
if (data.success === false) {
return res.status(400).json({ error: data.error.info });
}
return res.json(data);
} catch (error) {
console.error('Error fetching IP data:', error);
return res.status(500).json({ error: 'Failed to fetch geolocation data' });
}
});
// Endpoint to use my IP, added this for testing purposes (can skip)
app.get('/api/myip', (req, res) => {
// Get client IP from the request
const ip = req.headers['x-forwarded-for'] || req.socket.remoteAddress;
res.json({ ip });
});
// Serve the main HTML file
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});
Now that your backend is all set, let’s move on to building a nice front end!
Setting up Your Geolocation API Front End
For your front end, let’s start by creating a subfolder inside your main directory and call it public, then we want to create a new file called index.html in the public folder.
Now you can build your front end however you like using basic HTML/CSS.
Our frontend will include:
- A form to enter IP addresses for lookup
- A map to visualize the location
- Information panels to display the geolocation data
- Buttons to look up specific IPs or the user’s own IP
IP Geolocation Map
IP Geolocation Tracker
Basic Info
Search for an IP address to view details
Location
Connection
Additional Info
Note: If you copy mine above you’ll be missing my style.css file, which you can find on my GitHub here.
Now we have to create an app.js file in the same directory as your index.html. This file is in charge of adding functionality to your front-end page and utilizing the endpoints in your server file to parse the JSON data and plot it on the map!
We can start by adding our map to the front end by adding an event listener to initialize the map and add a tile layer to give us the actual map images
document.addEventListener('DOMContentLoaded', () => {
// Initialize map
const map = L.map('map').setView([0, 0], 2);
// Add tile layer - this gives us the actual map images
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
// We'll use this to store our marker
let marker;
Next, we are going to grab every DOM element we have on our front end so we can make changes based on what we get from our server to the front-end elements.
// Grab all the DOM elements we need
const ipInput = document.getElementById('ip-input');
const searchBtn = document.getElementById('search-btn');
const myIpBtn = document.getElementById('my-ip-btn');
const basicInfo = document.getElementById('basic-info');
const locationInfo = document.getElementById('location-info');
const connectionInfo = document.getElementById('connection-info');
const additionalInfo = document.getElementById('additional-info');
Now we are going to declare our asynchronous function that will call our server endpoint to get our geolocation data using IPstacks API.
// Function to get geolocation data
async function getGeolocation(ip) {
try {
const response = await fetch(`/api/geolocation/${ip}`);
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.error || 'Failed to fetch geolocation data');
}
return await response.json();
} catch (error) {
console.error('Error:', error);
basicInfo.innerHTML = `Error: ${error.message}
`;
return null;
}
}
Now we can create our update UI function which will populate our front end with the data we get from the server side back-end that makes the request to IPstacks API.
// Function to update the UI with geolocation data
function updateUI(data) {
if (!data) return;
// Update basic info
basicInfo.innerHTML = `
IP: ${data.ip}
Type: ${data.type}
Continent: ${data.continent_name}
Country: ${data.country_name} ${data.location?.country_flag_emoji || ''}
`;
// Update location info
locationInfo.innerHTML = `
Region: ${data.region_name || 'N/A'}
City: ${data.city || 'N/A'}
Zip Code: ${data.zip || 'N/A'}
Coordinates: ${data.latitude}, ${data.longitude}
`;
// Update connection info
connectionInfo.innerHTML = `
ASN: ${data.connection?.asn || 'N/A'}
ISP: ${data.connection?.isp || 'N/A'}
`;
// Update additional info
additionalInfo.innerHTML = `
Time Zone: ${data.time_zone?.id || 'N/A'}
Current Time: ${data.time_zone?.current_time || 'N/A'}
Currency: ${data.currency?.name || 'N/A'} (${data.currency?.symbol || 'N/A'})
Languages: ${data.location?.languages?.map(l => l.name).join(', ') || 'N/A'}
`;
// Update map if coordinates are available
if (data.latitude && data.longitude) {
const latLng = [data.latitude, data.longitude];
// Center the map on the coordinates
map.setView(latLng, 10);
// Add or update marker
if (marker) {
marker.setLatLng(latLng);
} else {
marker = L.marker(latLng).addTo(map);
}
// Add a popup with some location info
marker.bindPopup(`
${data.city || 'Unknown'}, ${data.region_name || ''}, ${data.country_name}
IP: ${data.ip}
Coordinates: ${data.latitude}, ${data.longitude}
`).openPopup();
}
}
Now let’s make a handler for our search button so when we type in an IP we can commence our request using this button.
// Handle search button click
searchBtn.addEventListener('click', async () => {
const ip = ipInput.value.trim();
if (!ip) {
basicInfo.innerHTML = `Please enter an IP address
`;
return;
}
const data = await getGeolocation(ip);
updateUI(data);
});
You can skip this but I am also going to add a button to use my IP address for testing purposes.
// Handle "Use My IP" button click
myIpBtn.addEventListener('click', async () => {
try {
// First get the client's IP
const response = await fetch('/api/myip');
const data = await response.json();
// Then get geolocation data for that IP
const geoData = await getGeolocation('myip'); // Using our special 'my' endpoint
updateUI(geoData);
// Update the input field with the IP
ipInput.value = data.ip;
} catch (error) {
console.error('Error getting client IP:', error);
basicInfo.innerHTML = `Error getting your IP: ${error.message}
`;
}
});
Finally, as a nice usability touch, I’m adding an event listener for the Enter key — so users can hit Enter to search instead of clicking the button
// Handle Enter key press in the input field
ipInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
searchBtn.click();
}
});
});
Visualising the Data
Now you’ve got all the pieces in place! Run your server with:
node server.js
Then open your browser to http://localhost:3000. You should see a clean interface with a map and some info panels. Try clicking “Use My IP” to see your location, or enter any IP address to look it up.
What’s happening behind the scenes:
- When you enter an IP or click “Use My IP”, the frontend makes a request to your Express server
- Your server calls the IPstack API to get geolocation data
- The data comes back to the client and gets displayed on the map and in the info panels
It’s a simple app, but it shows off the power of the IPstacks IP location API beautifully. There’s a lot of room to build on this foundation to impress your future interviewers!
Get Your Free
IP Geolocation Key!
IPstack
Join thousands of developers using ipstack for real-time IP intelligence!
Get Your Free API Key!100 Requests Free!
Looking to create a similar visitor-tracking tool for your website? Sign up for IPstack and start implementing geolocation features today!
Advanced Usage Scenarios
Now that we’ve got the basics down, we can level up our app with some more advanced features that IPstack’s geolocation API provides.
Bulk IP Lookups
Need to process a bunch of IP addresses at once? The bulk lookup endpoint can search up to 50 IP addresses at once.
We can implement bulk lookups in our application by creating an async function that takes an array of IP addresses, joins them with commas, and makes a single API request like the following:
async function bulkLookup(ipAddresses) {
// Join the IPs with commas
const ips = ipAddresses.join(',');
try {
const response = await fetch(
`https://api.ipstack.com/${ips}?access_key=${ACCESS_KEY}`
);
return await response.json();
} catch (error) {
console.error('Failed to fetch bulk IP data:', error);
return null;
}
}
// Example usage
const ipList = ['134.201.250.155', '72.229.28.185', '110.174.165.78'];
bulkLookup(ipList).then(results => {
results.forEach(location => {
console.log(`${location.ip}: ${location.city}, ${location.country_name}`);
});
});
This is super handy if you’re processing server logs or analyzing network traffic. Just remember that the free tier caps you at 100 requests per month, so use bulk lookups when you can to maximize your quota.
Security Module Integration
If you’re on a premium plan, you can tap into the security module to check if an IP is associated with any threats
The implementation into your application will look like the following:
async function checkIPSecurity(ipAddress) {
try {
const response = await fetch(
`https://api.ipstack.com/${ipAddress}?access_key=${ACCESS_KEY}&security=1`
);
const data = await response.json();
if (data.security) {
console.log(`Threat Level: ${data.security.threat_level}`);
console.log(`Is Proxy: ${data.security.is_proxy ? 'Yes' : 'No'}`);
console.log(`Is Tor: ${data.security.is_tor ? 'Yes' : 'No'}`);
if (data.security.threat_types) {
console.log(`Threat Types: ${data.security.threat_types.join(', ')}`);
}
}
return data;
} catch (error) {
console.error('Failed to check IP security:', error);
return null;
}
}
This is amazing for security-focused applications. You can use it to flag potentially dangerous IPs before they cause any harm.
Language Localization
Building an international app? You can get the geolocation data in different languages by adding a language parameter to your API request.
The API supports English (en), German (de), Spanish (es), French (fr), Japanese (ja), Portuguese Brazil (pt-br), Russian (ru), and Chinese (zh). This makes it easy to create multilingual applications with localized geolocation data.
The implementation in your app will look like the following:
async function getGeoInLanguage(ipAddress, language) {
try {
const response = await fetch(
`https://api.ipstack.com/${ipAddress}?access_key=${ACCESS_KEY}&language=${language}`
);
return await response.json();
} catch (error) {
console.error(`Failed to fetch geolocation in ${language}:`, error);
return null;
}
}
// Example: Get geolocation in German using the language code in ()
getGeoInLanguage('134.201.250.155', 'de').then(data => {
console.log(`Land: ${data.country_name}`); // Will show "Vereinigte Staaten" instead of "United States"
});
Performance Optimization Tips
When you’re ready to take your app to production, keep these performance tips in mind:
1. Bulk it up: Whenever possible, use bulk lookups instead of making separate API calls for each IP.
2. Be selective: If you only need specific fields, use the fields parameter to trim down the response:
const response = await fetch( `https://api.ipstack.com/134.201.250.155?access_key=ACCESS_KEY&fields=ip,country_name,city` );
3. Cache aggressively: IP geolocation data doesn’t change often, so cache it locally. Here is a simple caching example:
const geoCache = {};
async function getCachedGeolocation(ip) {
// Check if we have fresh cached data (less than a day old)
if (geoCache[ip] && (Date.now() - geoCache[ip].timestamp) < 86400000) {
console.log('Cache hit for IP:', ip);
return geoCache[ip].data;
}
// Cache miss - fetch fresh data
console.log('Cache miss for IP:', ip);
const data = await getGeolocation(ip);
// Store in cache with timestamp
if (data) {
geoCache[ip] = {
data,
timestamp: Date.now()
};
}
return data;
}
4. Implement error handling: Always include error handling to manage API timeouts, rate limiting, or service disruptions. A graceful fallback ensures your application remains functional in the event of a disruption.
Wrapping Up
You now have everything you need to build resume-worthy geolocation features with IPstack. We’ve covered making basic API calls, building a command-line tool, and creating a full-fledged web app with map visualization.
The applications for this are endless:
- Customize content based on visitor location
- Show prices in local currencies
- Implement geo-fencing for region-restricted content
- Detect suspicious logins from unexpected locations
- Track user demographics by region
Remember that while the free tier is great for development (100 requests/month), you’ll want to upgrade for production use. The paid plans start at just $9.99/month and give you higher request volumes, HTTPS support, and access to that sweet security module.
Get Your Free
IP Geolocation Key!
IPstack
Join thousands of developers using ipstack for real-time IP intelligence!
Get Your Free API Key!100 Requests Free!
Additional Sources
- Get your free IPstack API key
- IPstack API Documentation
- APILayer Marketplace FAQ
IP Geolocation API Implementation FAQs
What is an IP geolocation API and how does it work?
An IP geolocation API like IPstack translates IP addresses into geographic location data. When you send an IP address to the API, it returns structured data containing location information such as country, region, city, coordinates, and additional metadata by comparing the IP against highly accurate location databases.
How accurate is IP geolocation data from IPstack?
IPstack provides highly accurate location data at the country and city level. For precise location tracking at the street level, consider combining IPstack with other location methods like GPS or Wi-Fi positioning.
Can I use IPstack to track mobile device locations?
Yes, IPstack works for mobile devices connected to the internet. However, keep in mind that mobile carriers often use proxy IP addresses which may represent the location of the carrier’s servers rather than the exact device location. For precise mobile tracking, consider using IPstack alongside device-based location services.
What’s the difference between IPstack’s free and premium plans?
The free plan includes 100 API lookups per month with basic geolocation data, while premium plans offer higher request volumes, HTTPS encryption, additional data points (security module, connection type data), and advanced features like bulk lookups and language localization support.
How do I handle GDPR compliance when implementing geolocation?
When implementing IPstack, ensure you have a privacy policy that discloses the collection of IP addresses, clearly state why you’re collecting location data, implement consent mechanisms where required, and only store the minimum necessary data for your application’s functionality. IPstack’s data processing is GDPR compliant, but your implementation must also follow regulations.
Can I use IPstack for geofencing applications?
Yes, IPstack’s latitude and longitude data can be used to implement geofencing. You can set up virtual boundaries using coordinate polygons and trigger actions when users enter or leave these areas. The sample code in this article can be extended to create effective geofencing solutions.
How can I optimize API usage to stay within my plan limits?
Implement caching strategies to store IP data for a reasonable period (IPs rarely change location), use bulk lookups when checking multiple IPs, and consider implementing fallback logic for when you approach your API limits. Also, only request the specific data fields you need using the fields parameter.
Want to know: Key Differences Between Geofencing vs. Geolocation