Explain Codes LogoExplain Codes Logo

How to Get the Client's IP Address Using JavaScript?

javascript
web-development
promises
callbacks
Nikita BarsukovbyNikita Barsukov·Oct 6, 2024
TLDR

Get your client's IP address in a jiffy with a fetch call constructed for ipify. Insert this code directly into your JavaScript project:

fetch('https://api.ipify.org?format=json') .then(res => res.json()) .then(data => console.log(data.ip));

This should serve as a quick and straightforward solution for most needs.

Introducing IP Address User

Understanding that there are IPv4 and IPv6 is essential. Stay ahead of longer IP strings as more systems adapt to IPv6. While ipify is convenient and ideal for non-commercial use, limitations on the request quota and lack of SSL in particular plans might restrict you.

Always be aware of privacy regulations when you're dealing with user IP addresses.

Going Beyond: More Ways to Get IP

Method 1: Use WebRTC to Extract IP

The webrtc-ip library presents another way to retrieve local IP using WebRTC features, no external API required:

// Here's how it's done. No hocus-pocus, just JavaScript webrtcIp.getLocalIP().then(localIp => { console.log(`Local IP: ${localIp}`); });

Beware of the NAT issues and potential browser patching as WebRTC methodology may raise eyebrows on privacy practices.

Method 2: Bypass Cross-Domain Issues with JSONP

Cross-domain issues? JSONP to the rescue! JSONP provides the needed muscle against cross-domain problems, especially handy for supporting legacy browsers:

// Embrace the power of JSONP, supports legacy browsers too! function getIP(json) { console.log("My public IP address is:", json.ip); }

A Word on Service Stability

Remember that free IP services could go offline or be disrupted. If your application relies on a stable service, consider paid tiers instead. If adblockers get in the way, request users to disable them or find ways around them.

Handling Limitations: Tips and Tricks

Overcome Free Tier Usage Limits

Not exceeding the free tier usage limits is vital for most individual users. Monitor traffic to prevent interruptions.

Handling SSL Support Issues

If your service does not support SSL, consider upgrading or implementing your server-side solution.