Guides
Last updated
July 25, 2023

Get visitor IP address using Javascript

Emma Jagger
Emma Jagger

Table of Contents:

Get your free
IP Geolocation
 API key now
stars rating
4.8 from 1,863 votes
See why the best developers build on Abstract
START FOR FREE
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required

How to get client IP addresses using Javascript

Trying to build some customisation into your website? Or simply block some malicious IPs from accessing your content?

This guide covers the easiest way to retrieve a visitor IP address using javascript.

We will cover 2 methods:

  • The first will be using the open-source WebRTC method from diafygi
  • The second will use our simple and free IP geolocation API
Enter an IP address to start
Need inspiration? Try
73.162.0.1
VALIDATE
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
Checking
5
Results for
ip address
Country:
TEST
Region:
TEST
City:
TEST
Coordinates:
TEST
Zip code:
TEST
Connection:
TEST
Get free credits, more data, and faster results

Method 1: Use new WebRTC method

Important: This method is now no longer supported by several browsers.

Continue the reading below to see another free alternative.

This method uses diafygi "STUN IP Address requests for WebRTC".

This code snippet is based on newly-released WebRTC support in Chrome and Firefox that allows request for STUN servers to be made, resulting in the ability to access local and public IP addresses for your visitors. With a small Javascript code you could easily perform these requests and make the IP data available in other parts of your page to be analysed and use for customisation or blocking.

The good news is that these calls can't be blocked by ad blocking plugins and widgets because they are made outside of the XMLHttpRequest instance. Given that 20 to 30% of the internet users are browsing with Adblockers, this is perfect if you want to ensure aconsistent experience for all your users. Copy and paste the following code into your web page:



//get the IP addresses associated with an account
function getIPs(callback){
var ip_dups = {};

//compatibility for firefox and chrome
var RTCPeerConnection = window.RTCPeerConnection
|| window.mozRTCPeerConnection
|| window.webkitRTCPeerConnection;
var useWebKit = !!window.webkitRTCPeerConnection;

//bypass naive webrtc blocking using an iframe
if(!RTCPeerConnection){

var win = iframe.contentWindow;
RTCPeerConnection = win.RTCPeerConnection
|| win.mozRTCPeerConnection
|| win.webkitRTCPeerConnection;
useWebKit = !!win.webkitRTCPeerConnection;
}

//minimal requirements for data connection
var mediaConstraints = {
optional: [{RtpDataChannels: true}]
};

var servers = {iceServers: [{urls: "stun:stun.services.mozilla.com"}]};

//construct a new RTCPeerConnection
var pc = new RTCPeerConnection(servers, mediaConstraints);

function handleCandidate(candidate){
//match just the IP address
var ip_regex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/
var ip_addr = ip_regex.exec(candidate)[1];

//remove duplicates
if(ip_dups[ip_addr] === undefined)
callback(ip_addr);

ip_dups[ip_addr] = true;
}

//listen for candidate events
pc.onicecandidate = function(ice){

//skip non-candidate events
if(ice.candidate)
handleCandidate(ice.candidate.candidate);
};

//create a bogus data channel
pc.createDataChannel("");

//create an offer sdp
pc.createOffer(function(result){

//trigger the stun server request
pc.setLocalDescription(result, function(){}, function(){});

}, function(){});

//wait for a while to let everything done
setTimeout(function(){
//read candidate info from local description
var lines = pc.localDescription.sdp.split('\n');

lines.forEach(function(line){
if(line.indexOf('a=candidate:') === 0)
handleCandidate(line);
});
}, 1000);
}

//Test: Print the IP addresses into the console
getIPs(function(ip){console.log(ip);});

Now you can use the following function to get the IP as soon as it's found:



//Test: Print the IP addresses into the console
getIPs(function(ip){console.log(ip);});

There are several downsides to using this method. Not only is it not supported by a few browsers, but it also lacks certain information that you can otherwise tell from an IP address, such as whether the IP address is using a proxy or VPN.

Method 2: Use Abstract's IP detection API

Abstract provides a free IP detection API that has a method to retrieve the IP of a visitor.

This simple to use, yet powerful API provides the following features:

  • Retrieve the IP of a visitor
  • Retrieve the location of a visitor
  • Retrieve the location of an IP

The API is free to use and allow thousands of calls per month. Using it is pretty simple and only require an API key you can get for free by signing up here. The documentation can be found on the documentation page: ip geolocation documentation. In addition, you can see our review of the best IP geolocation API as well as try our "What is my IP address and location?" tool for non-technical users.

Frequently Asked Questions

Can JavaScript get a visitor's IP address directly in the browser?

No, browser-based JavaScript cannot access the client's IP address directly due to privacy and security restrictions. You need to use either an external IP detection API or, if working server-side, read it from the request object in Node.js.

What is the WebRTC method for getting an IP address in JavaScript, and why is it unreliable?

The WebRTC method uses RTCPeerConnection to make STUN server requests, which can expose both local and public IP addresses. However, several major browsers no longer support this technique, and ad blockers can interfere with it, making it unsuitable for production use.

What is the recommended way to get a visitor's IP address in JavaScript?

The most reliable approach is to call a third-party IP detection API using the Fetch API. Services like Abstract's IP Geolocation API return the visitor's public IP with a single request and no browser compatibility concerns. This method also works consistently across all modern browsers.

How do I get a user's IP address in JavaScript using an API?

Make a fetch call to an IP geolocation endpoint and read the returned IP field from the JSON response. Abstract's free API, for example, returns the visitor's IP along with location data in one call, so you don't need separate requests for additional context.

What extra data can I get alongside the IP address?

IP geolocation APIs typically return much more than just the IP address, including city, region, country, timezone, and flags for proxy or VPN usage. The WebRTC method provides only the raw IP, so API-based detection is the better choice when you need location or security signals.

Does getting a visitor's IP address in JavaScript work the same way in Node.js?

No. In Node.js you can read the IP directly from the incoming request object, typically via the remoteAddress property or the X-Forwarded-For header when running behind a proxy. This server-side approach does not require any external request and is generally more reliable than client-side methods.

Emma Jagger
Emma Jagger

Emma Jagger is an experienced engineer and Google alumna with a degree from Carnegie Mellon University. She specializes in email validation, IP geolocation, and API integration, focusing on creating practical and scalable solutions through her technical writing.

Get your free
IP Geolocation
key now
See why the best developers build on Abstract
get started for free

Related Articles

Get your free
IP Geolocation
key now
stars rating
4.8 from 1,863 votes
See why the best developers build on Abstract
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required