Disclosure: this guide is published on behalf of IP-API.io by an authorized representative, with AI-assisted drafting. It contains no customer addresses or live API key.
A cache keyed by the raw IP string can miss even when the network address has not changed. For example, 2001:0DB8:0000:0000:0000:0000:0000:0001 and 2001:db8::1 describe the same IPv6 address. A plain string comparison treats them as different keys. These are documentation addresses used only for local parsing examples; the code below does not perform a lookup.
The practical result is repeated enrichment work, inconsistent cache hits and confusing batch statistics. Lowercasing the input solves the letter case difference, but it does not compress zero groups or reconcile other equivalent IPv6 spellings.
Define what the input means first
This function accepts one bare IPv4 or IPv6 address. It deliberately rejects hostnames, CIDR ranges, address-and-port strings, bracketed URL hosts, surrounding whitespace and scoped addresses such as fe80::1%eth0. Those inputs belong to different parsing contracts. If your application accepts them, parse them explicitly at that boundary rather than quietly broadening this function.
Node’s net.isIP distinguishes IPv4 and IPv6 and rejects invalid input. Its IPv4 check uses dotted decimal with no leading zeroes. That strict check comes before the URL parser: this prevents a hostname or an alternate IPv4 URL spelling from entering through a permissive URL input.
Validate, then serialize IPv6
import { isIP } from 'node:net'; export function canonicalIp(input) { if (typeof input !== 'string' || input !== input.trim() || input.includes('%')) { throw new TypeError('Expected an unscoped IP address without whitespace'); } const family = isIP(input); if (family === 4) return `v4:${input}`; if (family === 6) return `v6:${new URL(`http://[${input}]/`).hostname.slice(1, -1)}`; throw new TypeError('Expected a bare IPv4 or IPv6 address'); } The URL object is used only to serialize an already validated IPv6 host. Constructing it makes no HTTP request. The http:// scheme is a local parsing wrapper, not the transport for an API call. The brackets are removed from the resulting hostname because this function returns a cache-key component rather than a URL.
The v4: and v6: prefixes are part of the key contract. In particular, an IPv4-mapped IPv6 address remains in the IPv6 family. ::ffff:192.0.2.1 and ::ffff:c000:201 normalize together, while 192.0.2.1 keeps a separate key. Whether your application should equate mapped IPv6 with native IPv4 is a separate policy decision. Do not silently introduce that decision while fixing string formatting.
Test the equivalence classes you actually support
import assert from 'node:assert/strict'; assert.equal(canonicalIp('2001:0DB8:0:0:0:0:0:1'), 'v6:2001:db8::1'); assert.equal(canonicalIp('2001:db8::1'), 'v6:2001:db8::1'); assert.equal(canonicalIp('192.0.2.1'), 'v4:192.0.2.1'); assert.equal(canonicalIp('::ffff:192.0.2.1'), canonicalIp('::ffff:c000:201')); assert.notEqual(canonicalIp('192.0.2.1'), canonicalIp('::ffff:192.0.2.1')); assert.throws(() => canonicalIp('fe80::1%eth0'), TypeError); I checked the function on Node v26.14.0 with 18 assertions, including invalid values, ports, brackets, whitespace, leading-zero IPv4, scoped IPv6 and a Map that receives two aliases but retains one entry. No API key or network request was used. Run the tests on the Node versions your application supports; this is a small normalization helper, not a general network-address policy library.
Put the normalized address inside a larger cache contract
A canonical address alone is insufficient when the response depends on a provider, tool, requested fields, API version or customer policy. Include the dimensions that actually change the result. If your service isolates customer data, preserve that isolation in the key and storage boundary. Avoid composing ambiguous keys from unescaped, user-controlled separators.
Keep successful responses separate from authentication errors, quota exhaustion and transport failures. An unavailable lookup is not an empty geolocation result. Choose expiration according to how much staleness the consuming feature can tolerate, and retain the lookup time so an operator can see the age of the context.
For IP-API.io’s JavaScript integration, normalize at the application boundary before constructing your cache key or assembling a batch. Keep the provider call’s address separate from any internal key prefix: do not send v6:2001:db8::1 as an IP argument. Follow the API reference for the actual request shape.
At the time of writing, the €0/month Free plan includes 1,000 IP requests and 100 email validations per billing month, with an account and API key required. Reducing duplicate work is useful, but a local canonicalizer does not establish how a provider meters a batch. Check current quota rules and measure actual usage rather than inferring billing from the number of cache keys.
Finally, this key is still an IP address. Canonicalization does not anonymize it, establish that it came from the visitor, decide whether it is public, or prove that a network flag identifies a person. Keep provenance, retention and interpretation as explicit application decisions.
