To most people, an IP address is just that—the address of a device on the internet. But for application developers, it is an incredibly valuable piece of information. Over the years, countless bytes of information have been collected and cataloged about almost every device that has accessed the internet, and by using ipdata’s API, application developers can access a tremendous amount of location-oriented data to enhance their users’ experience.
But of course, you need an IP address before you can use the wealth of information provided by ipdata. In this article, you will learn how to retrieve an IP addresses with JavaScript—both from within the browser and in your server application.
Retrieving Your User’s IP in the Browser
The browser is the OS of the web, and with more processing being handled within the browser, it makes some sense to retrieve the user’s IP address so that you can use it in your client-side code. The problem, however, is that the browser doesn’t expose any network-oriented information about the device.
1. Using ipdata
You must therefore rely upon a web service to provide that information for you. You could write your own service as part of your server-side application, or you can use a third-party solution to retrieve your user’s IP address. ipdata’s web service is a perfect solution for this problem. All you need is an API key (go ahead and sign up for free). For example:
function json(url) {
return fetch(url).then(res => res.json());
}
let apiKey = 'your_api_key';
json(`https://api.ipdata.co?api-key=${apiKey}`).then(data => {
console.log(data.ip);
console.log(data.city);
console.log(data.country_code);
// so many more properties
});
This code defines a helper function called json()
. It simplifies the process of using fetch()
with resources that return a JSON structure, as most APIs do. Next, the json()
function is used to send a GET request to ipdata’s default endpoint: http://api.ipdata.co. You can use this endpoint to query any IP address, but if you do not provide one with the request, the web service uses the address of the device that issued the request: the browser in this case.
The web service returns a JSON payload that contains a wealth of information—not just the user’s IP address, but all the locational data that ipdata has about that address. For example: the ISP, city, state, country, continent, etc are provided in the payload. Because of this, you do not need to issue any other HTTP requests because you already have the information you need.
Sometimes, however, you do not need all the extraneous locational information, and ipdata’s API lets you filter the results by including the fields
query parameter. For example:
json(`https://api.ipdata.co?api-key=${apiKey}&fields=ip`).then(data => {
console.log(data.ip);
});
The JSON payload contains only the fields specified by the fields
query parameter. So, in this code, the resulting JavaScript object (named data
) has a single property called ip
.
2. Using Cloudflare
ipdata's web service is very easy to use. However, another (albeit limited) option is CloudFlare’s trace utility found at https://www.cloudflare.com/cdn-cgi/trace. It returns a plain-text set of key/value pairs, and the following shows a condensed example of the format:
h=www.cloudflare.com
ip=178.25.55.75
ts=1605854122.426
visit_scheme=https
uag=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.193 Safari/537.36
As you can see, the output contains an ip
key with its associated value, and you can parse it out with a regular expression like this:
function text(url) {
return fetch(url).then(res => res.text());
}
text('https://www.cloudflare.com/cdn-cgi/trace').then(data => {
let ipRegex = /[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}/
let ip = data.match(ipRegex)[0];
console.log(ip);
});
This code defines a text()
helper function that is similar to json()
, but of course, it reads the response stream as text instead of a JSON structure.
Inside the callback function, you define a regular expression that matches an IPv4 address, and you use that regex to find a match within the response payload. The result gives you the user’s IP address that you can then use in your client-side code.
3. Using Amazon
A similar utility provided by AWS provides another reliable option to query your user’s IP address.
function getIPFromAmazon() {
fetch("https://checkip.amazonaws.com/").then(res => res.text()).then(data => console.log(data))
}
getIPFromAmazon()
This will give you
178.25.55.75
Retrieving the Client’s IP in the Server (NodeJS)
IP stands for Internet Protocol, and it implements a type of networking called packet switching. It has the concept of hosts (machines), and it defines how data, in the form of packets, are sent between the hosts. In the case of HTTP, there are two hosts: client and server.
When a browser issues an HTTP request to a server, the request is transmitted from the client to the server in the form of IP packets. These packets contain a variety of information, but there are two particularly important things that every packet has: the source host address and the destination host address. Because every packet contains the client address, your server application can retrieve the client’s IP address from the packet.
Every framework, regardless of language and/or platform, has some mechanism for retrieving the client’s IP address. For Node.js applications, there are two such mechanisms:
- the
x-forwarded-for
header. - the
request.connection.remoteAddress
property.
There is a slight issue, however; the x-forwarded-for
header can contain multiple, comma-separated IP addresses. Thankfully, the first IP address in the x-forwarded-for
header is typically the correct IP address. With that in mind, consider the following code:
const http = require('http');
function requestListener(req, res) {
let forwarded = req.headers['x-forwarded-for']
let ip = forwarded ? forwarded.split(/, /)[0] : req.connection.remoteAddress;
res.writeHead(200);
res.end(ip);
}
const server = http.createServer(requestListener);
server.listen(3000);
console.log('Server listening at http://localhost:3000');
A lot of this code is boilerplate, so let’s focus on the requestListener()
function. The first line of the function retrieves the value of the x-forwarded-for
header. It is not always guaranteed to be present. So, in the second line, you check if there is a value, and if so, you split it on a comma (,
) and use the first item in the resulting array. If the x-forwarded-for
header doesn’t exist, then you use req.connection.remoteAddress
as a fallback.
Viola! You have the client’s IP address. It may not be 100% accurate (the end-user could be using a VPN to mask their true IP), but it is more reliable than getting the client’s address through the browser.
Customize Your Content with IPs
As you can see, using JavaScript to find an IP address is relatively simple, and it’s likely that you’ll want to do something with that address. Maybe you’ll want to show different promotions or ads to your users based upon their region, or you may need to convert currency on the fly. Regardless of your needs, ipdata’s web service provides comprehensive locational information based upon your user’s IP address. Go ahead and setup an account for free. It only takes a couple of minutes to get an API key, and you can use it experiment with the API to see what it can do for you.