I need to find a way to get the client’s IP address using only JavaScript, with no server-side code or SSI. I’m open to using a free third-party service or script. What’s the best method to JavaScript get IP address without involving server-side code?
Well, from my experience, the easiest way to javascript get ip address is to use a free external API. A solid choice I’ve used in projects is ipify. It’s incredibly simple. You just make a GET request to their API, and voilà! Here’s a basic example:
fetch('https://api.ipify.org?format=json')
.then(response => response.json())
.then(data => console.log('Your IP is:', data.ip))
.catch(err => console.error('Error fetching IP:', err));
I’ve used this in dashboards during development to log visitor info. It’s clean, reliable, and takes just seconds to implement. Totally recommend it for quick setups.
Definitely! If you’re looking to javascript get ip address and also gather some more detailed information, like the user’s city, region, or country, another great option is ipinfo.io. They offer a free tier with up to 50,000 requests a month (you just need to sign up for an API token). This can be a real bonus for apps that need geolocation features. Here’s an example:
fetch('https://ipinfo.io/json?token=YOUR_TOKEN_HERE')
.then(response => response.json())
.then(data => {
console.log('IP Address:', data.ip);
console.log('City:', data.city);
console.log('Region:', data.region);
})
.catch(err => console.error('IP info fetch failed:', err));
This method provides richer data compared to ipify, so it’s a great choice if you need geolocation features integrated into your application.
Both of those are fantastic approaches for a public IP address, but if you’re working on something a bit more experimental and want to javascript get ip address from within the local network (like 192.168.x.x), there’s a cool (though somewhat hacky) method using WebRTC. I’ve played around with this when I needed the local IP for some specific use cases. Here’s a little code snippet:
const pc = new RTCPeerConnection({iceServers: []});
pc.createDataChannel('');
pc.createOffer().then(offer => pc.setLocalDescription(offer));
pc.onicecandidate = event => {
if (!event || !event.candidate) return;
const ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3})/;
const ip = ipRegex.exec(event.candidate.candidate)[1];
console.log('Local IP Address:', ip);
pc.close();
};
Just a heads up, this method only gets the local IP, and browser support for this is rapidly tightening due to privacy concerns, so it’s a bonus hack for now. It’s fun to try out, though!