How to Get the IP Address in JavaScript

So you’re looking to extract an IP address using JavaScript? Well, you’re in the right place.

Today, we’re going to dive into the details of how to get an IP address, no matter what situation or setup you have. Whether you need the IP in a browser or the IP of your server this post will answer your questions.

We’ll even go one step further to show you how you can enrich your IP data to get additional details about your IP that you may need to build your application features.

By the end of this post, you’ll understand how to get a user’s IP address on a browser, a request IP in a server, or an IP of your a server.

The Three IPs

There are three likely scenarios in which you’re trying to get an IP address in JavaScript. Those are:

  1. The browser: You need the IP address of a user on your front-end application to show country-specific information, local weather, or other details.
  2. The request: You need the IP address from a given request to your back-end to block (or allow) a certain IP address.
  3. The server: You need the IP of the actual server the application code is running on for logging or debugging.

Let’s go through each scenario in turn. From there, we’ll find a solution that works for your situation.

1. Retrieving an IP in the Browser

Let’s take the first scenario, in which you need to access a user’s IP in the browser.

How do we go about doing that?

Unfortunately, the short answer is…it’s not simple. But why not? The reason is that a traditional browser request doesn’t return any user IP data, and there’s no foolproof way of retrieve the user’s IP while on a browser.

Now, I know what you’re thinking: “Urgh, really?” But yes, you’re just going to have to trust me on this one. You’ll find some hacks if you scour the internet—but they don’t work consistently. The reality is that we’re going to need some server-side help. Fortunately, we have a few options.

Our two main options are to use an existing web service or to modify our own server. Each approach has its own advantages and trade-offs, so let’s go through those to see which one suits your needs.

Option 1: Use an Existing Service

Some unpaid IP APIs will return you the IP address of the caller (your browser) when you make a request to them. For instance, this is what would happen in the below example, where we’re calling a CloudFlare API in order to retrieve the browser’s own IP. The browser’s IP can be then used for processing.

        const API_URL = ``;
        function onDataRecieve() {
            const ipRegex = /[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/                           
            const IP = xhttp.responseText.match(ipRegex)[0];
            document.getElementById("demo").innerHTML = IP
        const xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = onDataRecieve;"GET", API_URL, true);
    <div id="demo"></div>

You can run the above code in your application (by copying it into a file with the extension .html and opening it in your browser). But be warned that this code is not a long-term solution—there are a couple of downsides to consider when using a third-party service like CloudFlare’s API. What do I mean? Let me explain.

Firstly, the API response is not in your control. In CloudFlare’s example, the response is plain text, and CloudFlare maintains no official contract. Not having an official API contract means that CloudFlare’s API is subject to breaking at a moment’s notice.

Secondly, not only could the contract break, but the API service also could start denying your requests. If CloudFlare sees a lot of requests coming from your application, they’re likely to start blocking them to protect their system. Third-party APIs have no obligation to ensure that their API is working for you.

So, if the above example works for you but you need a foolproof solution that’s production ready, you’re going to need to make some server changes yourself. Which brings us to our second option.

Option 2: Modify Your Own Server

The alternative to using a service such as CloudFlare’s API is to use a paid IP service that has an SLA and assurance that the contract won’t change and the API won’t be taken down.

But before you go ahead thinking “Perfect, sign me up!,” there’s one thing to consider: Paid APIs usually grant access via an API key (or some form of similar authentication). You don’t want to expose your API key in the browser, as anyone could then copy the key for their own use.

With that in mind the following snippet will show, for demonstration purposes only, how you can call out to an external web service and receive back a response with an IP address. For the example, we’re using

        const API_KEY = 'YOUR_API_KEY';
        const API_URL = `${API_KEY}`;
        function onDataRecieve() {
            const { ip } = JSON.parse(xhttp.responseText);
            document.getElementById("demo").innerHTML = ip;
        const xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = onDataRecieve;"GET", API_URL, true); xhttp.send();
    <div id="demo"></div>

To protect your API key, you’ll want to set up a proxy server that calls the paid API from your server on your behalf. Having a proxy ensures that the API key is hidden and that only your application can make requests to the paid service.

That covers the ways that you can get an IP on a browser, but what if you’ve got an application that’s rendered on the server? Or what if you have an API that needs to access an IP? Let’s take a look at that now.

2. Retrieving a Server Request IP

Getting an IP address on the back end is a different ball game from accessing an IP on the back end. Why? Accessing the IP on the back end requires knowledge about how you’ve got your server setup. The below code example caters to the different server setups that you might have. Let’s take a look at the different server setups and how you can get the IP in the different situations.

const http = require('http');
const requestListener = function (req, res) {    
    var ip = (
        req.headers['x-forwarded-for'] ||
        req.connection.remoteAddress ||
        req.socket.remoteAddress ||(req.connection.socket ? req.connection.socket.remoteAddress : null)
const server = http.createServer(requestListener);

The most likely place you’ll find the IP on the server is in the x-forwarded-for header, which most load balancers use when forwarding requests to an application server. If the IP address is not in the header, it might be found from the request connection object or from the socket details (if the request originates from a socket). The code above creates a Node.js API, which checks finds the IP from the correct source and returns the found IP as an API response.

Now let’s take a look at the last scenario, in which you need to access the IP of your application server.

3. Retrieving the Application Server IP

Accessing your own server IP is useful for reporting issues related to that specific server such as downtime or failed requests to an instance. And getting your own IP address while on your own server is more straightforward since the IP won’t likely come from multiple places as it did for our user requests.

var os = require('os');
var networkInterfaces = os.networkInterfaces();

You can use the snippet above to grab all your network interfaces of the server you’re running on. Depending on which network interfaces you’re using, you’ll find your IP within the response from the network interfaces method.

However, since the IPs given in the network interfaces method are often private network IPs, if you want the public IP you may want to implement a solution as discussed in section 1 that calls out to the public internet.

The specifics of why these network interface values might not be your public IP, and therefore potentially not what you’re after, is too big of a question to answer comprehensively in today’s post. But I’ll give you the short answer: The addresses returned from the network interfaces method are usually private IPs, and privately networked addresses are not on the public internet, so only computers in that network can access them.

Enriching Your IP Data

Getting the IP address using JavaScript might be the first hurdle you’re trying to get over. But it’s likely that you want to access your IP address for a certain reason, and the IP might not be enough on its own.

By running an IP through an external service such as IPData. you can get enriched data about that IP address. You can then use that information to do things like perform re-routing based on country, block malicious IP addresses, and more.

If you want to get started, you can set up an account for free—it takes a couple of minutes to get an API key and then experiment with the API to see what it can do for you.

IP Address in JavaScript: Solved

And that covers everything for today. Hopefully you were able to find a solution for getting the IP address in JavaScript that works for you.But before you go, don’t forget to try out the IP enriching API service we discussed. You might find that the additional data helps you achieve the feature you’re trying to implement!

This post was written by Lou Bichard. Lou is a JavaScript full stack engineer with a passion for culture, approach, and delivery. He believes the best products emerge from high performing teams and practices. Lou is a fan and advocate of old-school lean and systems thinking, XP, continuous delivery, and DevOps.

Tags :

The ipdata Team

Build location aware applications on the most reliable IP Geolocation service.