Skip to main content

Command Palette

Search for a command to run...

How to Get IP Address Using JavaScript With IP Checker API?

Learn how to detect a visitor’s IP address with JavaScript, enrich it with geolocation data, and use IP signals for fraud detection.

Updated
•7 min read•View as Markdown
How to Get IP Address Using JavaScript With IP Checker API?

You ship a checkout page, and within a week orders start arriving from cities you have never shipped to. Your pricing page shows dollars to visitors in Berlin. Your signup form gets hit by forty accounts from the same network overnight. Three different problems, one shared root cause: you have no idea where your visitors are connecting from.

The frustrating part is that JavaScript cannot simply read it. That is why so many developers search for get ip address using javascript and end up copying snippets that quietly stopped working years ago.

In this tutorial, you will build a small Node.js service that fixes that. In three steps, it detects the visitor's IP address, enriches it with location and network data, and produces a simple risk score you can plug into your signup or checkout flow.

What Do You Need Before You Start?

Not much: Node 18 or newer, a basic grasp of Express, and a free API key.

  1. Node.js 18 or later installed, since the native fetch API is built in

  2. The Express package, added with npm install express

  3. A free access key from ipstack, which takes about two minutes to create

That is the whole setup. Everything else runs on your machine.

Why Doesn't JavaScript Know the Visitor's IP Address?

Because the browser sandbox was designed to keep it hidden.

A public IP belongs to the network a visitor connects through, not to the device or the webpage. Handing it to every script on every site would be a privacy problem, so no standard browser API exposes it. Older tutorials relied on a WebRTC leak that revealed internal and sometimes public addresses, but modern browsers now mask those candidates behind scrambled mDNS hostnames, so those snippets return nothing useful today.

The conclusion is simple: any working solution has to step outside the browser. Your own server observes the request, or a service does and tells you what it saw.

Which Method Should You Use to Get the IP?

Three methods work in production today, and they differ mainly in how much context they give back.

Method 1: read request headers. When traffic reaches your server, the connection carries its source address, usually in the forwarded header behind a proxy or CDN. The upside is zero external dependencies and full control of the data path. The tradeoff is that you get a bare address with no context, and headers can be spoofed if requests do not pass through a trusted proxy.

Method 2: call a public echo endpoint. A single fetch to a service that returns the caller's address is tempting because it is one line of code. The upside is instant setup. The tradeoff is that you send user data to a domain you do not control, and CORS changes or rate limits can break it without warning.

Method 3: use a dedicated IP intelligence service. These combine the lookup with enrichment: country, city, coordinates, ASN, currency, time zone, and proxy or VPN flags depending on the plan. The upside is that one call returns identity plus context. The tradeoff is an extra dependency and usage based pricing, which caching largely offsets.

We will use Method 1 in Step 1 and Method 3 in Step 2, which mirrors how real applications are built.

Step 1: How Do You Capture the Client IP in Express?

By reading the forwarded header and falling back to the socket address.

Create a file called server.js and add this:

const express = require('express');
const app = express();

// behind a proxy or CDN, this makes Express trust forwarded headers
app.set('trust proxy', true);

app.get('/whoami', (req, res) => {
  const ip =
    req.headers['x-forwarded-for']?.split(',')[0].trim() ||
    req.socket.remoteAddress;
  res.json({ ip });
});

app.listen(3000, () => console.log('Listening on port 3000'));

Run it and test locally with curl http://localhost:3000/whoami. Behind a real proxy, the first entry in the forwarded list is your visitor; anything after it belongs to intermediate hops, which is why the code splits and takes the first value.

One caution: only trust the header when requests actually pass through your proxy. Direct requests can forge it, so keep trust proxy configured to match your real infrastructure.

Step 2: How Do You Turn That IP Into Location Data?

By calling a lookup endpoint and mapping the fields you need into a context object.

Add an enrichment function to your service:

const API_KEY = process.env.IPSTACK_KEY;

async function getGeoContext(ip) {
  const url = `https://api.ipstack.com/${ip}?access_key=${API_KEY}`;
  const data = await fetch(url).then(r => r.json());

  return {
    country: data.country_name,  // "United States"
    city: data.city,             // "Mountain View"
    lat: data.latitude,
    lon: data.longitude,
    asn: data.connection?.asn,   // network operator
  };
}

If you want the caller's own address without parsing headers at all, the same service offers a check endpoint that resolves the requesting IP automatically:

const data = await fetch(
  `https://api.ipstack.com/check?access_key=${API_KEY}`
).then(r => r.json());

Two habits will save you headaches here. First, keep the access key in an environment variable, because anything shipped to the browser is public. Second, cache results per address for 24 hours, since IPs rarely change and your quota will stretch much further:

const cache = new Map();

async function getGeoCached(ip) {
  if (cache.has(ip)) return cache.get(ip);
  const ctx = await getGeoContext(ip);
  cache.set(ip, ctx);
  setTimeout(() => cache.delete(ip), 24 * 60 * 60 * 1000);
  return ctx;
}

If you are still comparing providers, evaluate each ip checker api against four things: IPv6 coverage, whether security fields like proxy flags are included in your plan, documentation quality, and response time from your server's region.

Step 3: How Do You Turn the Data Into a Risk Score?

By comparing the IP signals against what the user claims and scoring every mismatch.

The stakes justify the effort. Juniper Research projects that online payment fraud will cost businesses more than $343 billion cumulatively between 2023 and 2027, and much of it flows through transactions where something geographic failed to add up. This pattern, often called ip geolocation for fraud detection, layers a few simple checks:

  1. A billing country that does not match the IP country

  2. Impossible travel, like logins from Berlin and Singapore forty minutes apart

  3. Connections arriving from datacenter or VPN ranges

  4. Bursts of signups from a single subnet

Here is a minimal scoring function:

function scoreSession(session, geo) {
  let risk = 0;

  if (session.billingCountry && session.billingCountry !== geo.country) {
    risk += 30;  // billing country does not match IP country
  }
  if (geo.connection?.type === 'hosting') {
    risk += 30;  // request came from a datacenter range
  }
  if (session.lastCountry && session.lastCountry !== geo.country) {
    risk += 20;  // possible travel, confirm with timestamps
  }

  return risk;  // 0 is clean, 80 or more needs review
}

Wire it into your signup route, then act on thresholds: a score above 50 triggers a step up challenge such as an email verification, and anything above 80 routes to manual review. Treat the score as a signal rather than a verdict. Legitimate customers travel and use VPNs, so the goal is friction for obvious abuse, not punishment for everyone else.

That is the complete loop: capture the IP, enrich it, score it. Point the service at your own traffic for a day and watch what comes back. From there, natural extensions include a Redis backed cache, logging scores per session, and feeding the output into your existing fraud rules.

Frequently Asked Questions

Can I Get a Visitor's IP With Client Side JavaScript Alone?

No. The browser sandbox never exposes the public address to scripts running on the page. Your server has to read the request headers, or a lookup service has to observe and enrich the incoming request for you.

How Accurate Is IP Geolocation?

Country level results are dependable, typically clearing 95 percent accuracy in commercial databases. City level results are estimates, landing between 60 and 80 percent accuracy depending on region, so treat them as regional context rather than a street address.

For fraud prevention and personalization, you generally operate under legitimate interest, but an IP address counts as personal data under GDPR and similar laws. Disclose the practice in your privacy policy, document your purpose, and avoid retaining precise location data longer than you need it.