Copied to clipboard
Embed

Know where your visitor is, with one tag

Show a visitor their country, pick a currency, or change a shipping notice without writing the request yourself. The script asks our API once per visit, keeps the answer in the visitor’s own browser, and fills in your page.

  • Free, no key
  • One request per visit
  • No cookies
  • About 3 KB
Your page
<script src="https://ipaddress.to/embed/v1/" async crossorigin
  data-fields="location.country,location.currency">
</script>

Shipping to <b data-ipa="location.country">your
country</b>, prices in
<span data-ipa="location.currency.code">USD</span>.
What a visitor in Canada seesShipping to Canada, prices in CAD.

Quick start

Put the script anywhere on the page, then mark the elements that should receive a value with data-ipa. Whatever you write inside the element is the fallback: it stays if the value is unknown, the request fails, or the visitor blocks scripts.

HTML
<script src="https://ipaddress.to/embed/v1/" async crossorigin
        data-fields="location.country,location.country_code,location.currency"></script>

<p>
  Shipping to <b data-ipa="location.country">your country</b>,
  prices in <span data-ipa="location.currency.code">USD</span>.
</p>

That is the whole integration. A visitor in Canada sees “Shipping to Canada, prices in CAD.” Everyone else sees their own country, and anyone the lookup cannot place sees the text you wrote.

Press the button to load the script and look up your own address.

Script tag options

All optional. Set them as attributes on the script tag.

data-fields
string
Comma-separated list of the fields you use, e.g. location.country_code,location.currency. The API then returns only those, which makes the response a few hundred bytes instead of about 1 KB. Leave it out to get everything. See the field list.
data-cache
string
session (default) remembers the answer until the tab is closed. local remembers it across visits. off asks every time.
data-max-age
seconds
How long a remembered answer is trusted. Default 1800 (30 minutes). A visitor who switches networks gets a fresh answer once it expires.
data-timeout
ms
Give up after this long and keep the fallback text. Default 4000.
data-auto
flag
Run the lookup on page load even when the page has no data-ipa elements. Use it when you only want the CSS classes or the event.
data-key
string
Your API key, if you want these requests counted on your account page. A key in a web page is visible to anyone, so use one you created for this site only.

Without data-auto and without any data-ipa element, the script loads and does nothing until you call it from JavaScript. No request is made.

Filling the page from HTML

data-ipa
path
The field to show, as a dotted path into the response: location.city, location.currency.code, asn.org. The element’s text is replaced with the value.
data-ipa-attr
attribute
Write the value into an attribute instead of the text. If the attribute contains {value}, only that token is replaced (and URL-encoded). Event-handler attributes are refused.
data-ipa-show
list
Show the element only when the value is in the list, hide it otherwise. Case-insensitive.
data-ipa-hide
list
The reverse: hide the element when the value is in the list.
HTML
<!-- a link that carries the visitor's country -->
<a data-ipa="location.country_code" data-ipa-attr="href"
   href="/stores?country={value}">Find a store near you</a>

<!-- a notice for some countries only -->
<p data-ipa="location.country_code" data-ipa-show="CA,US" hidden>
  Free shipping across North America.
</p>

<!-- and one for everyone else -->
<p data-ipa="location.country_code" data-ipa-hide="CA,US">
  International shipping from $12.
</p>

Start elements that should be hidden by default with the hidden attribute, as in the first notice above, so nothing flashes before the answer arrives.

CSS classes

After a successful lookup the script adds classes to the <html> element, so simple cases need no JavaScript at all.

ipa-ready
class
The lookup finished and the page has been filled.
ipa-cc-xx
class
The visitor’s country as a lower-case ISO code: ipa-cc-us, ipa-cc-de. Needs location.country_code in your field list.
ipa-eu
class
The country is an EU member state. Needs location.is_eu_member.
ipa-vpn
class
The address is a known VPN, proxy or Tor exit. Needs is_vpn, is_proxy, is_tor.
ipa-failed
class
The lookup failed or timed out. Fallback text is in place.
CSS
.vat-notice              { display: none; }
.ipa-eu .vat-notice      { display: block; }

.price-gbp               { display: none; }
.ipa-cc-gb .price-gbp    { display: inline; }
.ipa-cc-gb .price-usd    { display: none; }

JavaScript API

The script defines one global, IPAddressTo. Because the tag is async, wait for it before calling: either put your code in the tag’s onload, or listen for the event described below.

locate(options)
Promise
Returns the lookup for the current visitor. Uses the remembered answer when there is one; otherwise makes one request. Calls made at the same moment share that request. Rejects on failure or timeout.
fill(root, options)
Promise
Runs locate() and fills every data-ipa element under root (default: the whole document). Call it again after you add elements to the page, for example in a single-page app. It costs no extra request.
get(data, path)
any
Reads a dotted path from a result: IPAddressTo.get(data, "location.currency.code"). Returns undefined instead of throwing when part of the path is missing.
clear()
–
Forgets the remembered answer in this browser.
version
string
Script version, e.g. 1.0.1.

options takes the same settings as the tag, in camel case: fields (string or array), cache ("session", "local" or false), maxAge, timeout, key. Options passed to a call override the attributes on the tag.

JavaScript
<script src="https://ipaddress.to/embed/v1/" async crossorigin onload="pickCurrency()"></script>
<script>
function pickCurrency() {
  IPAddressTo.locate({ fields: ['location.country_code', 'location.currency.code'] })
    .then(function (data) {
      var currency = data.location.currency ? data.location.currency.code : 'USD';
      document.querySelector('#currency').value = currency;
    })
    .catch(function () {
      // Lookup failed or timed out. Keep your default and carry on.
    });
}
</script>

Events

In automatic mode the script reports the outcome on document, so code elsewhere on the page can react without knowing when the script loaded.

ipaddressto:ready
event
event.detail is the lookup result.
ipaddressto:error
event
event.detail.message says why: timeout, a network error, or the API’s error text.
JavaScript
document.addEventListener('ipaddressto:ready', function (event) {
  var where = event.detail.location;
  analytics.track('visitor_country', { country: where.country_code });
});

Fields

Ask only for what the page uses. Name a single value (location.country_code) or a whole group (location). The ones storefronts use most:

location.country
string
Country name in English, e.g. Canada.
location.country_code
string
Two-letter ISO code, e.g. CA.
location.state
string
Region, state or province.
location.city
string
City. An estimate: fine for a greeting, not for a delivery address.
location.timezone
string
IANA time zone, e.g. America/Toronto.
location.currency
object
code (CAD) and name (Canadian Dollar).
location.calling_code
string
International dialling prefix, for phone fields.
location.languages
string
Main languages of the country.
location.is_eu_member
boolean
Whether the country is in the European Union.
is_vpn, is_proxy, is_tor
boolean
Whether the address is a known anonymizer. The location of such a visitor is the location of the exit, not the person.
ip
string
The visitor’s public address.

The complete response is shown under IP Lookup. Every field there can be requested the same way.

Without the script

If you would rather make the request yourself, the same fields option works on the plain endpoint. Please remember the answer for the rest of the visit: a visitor’s country does not change between your product page and your cart, and one request per visit is faster for them than one per page.

JavaScript
async function visitorCountry() {
  const saved = sessionStorage.getItem('visitor-country');
  if (saved) return JSON.parse(saved);

  const res = await fetch(
    'https://ipaddress.to/api/lookup/my?fields=location.country_code,location.currency'
  );
  const data = await res.json();
  if (!data.success) throw new Error(data.error);

  sessionStorage.setItem('visitor-country', JSON.stringify(data));
  return data;
}
Response
{
  "success": true,
  "location": {
    "country_code": "CA",
    "currency": { "code": "CAD", "name": "Canadian Dollar" }
  }
}

How it behaves

Requests
One per visitor per browser session, however many pages they open. None at all on pages that neither mark an element nor call the API.
Page speed
Loaded with async, the script never blocks rendering. If our service is slow or down, the visitor sees your fallback text after the timeout and nothing else on the page is affected.
Speed
Keep the crossorigin attribute on the tag. With it, the browser makes the lookup over the connection it opened to fetch the script; without it, it opens a second connection first, which costs two extra round trips. Asking for only the fields you use also skips work on our side: a country-and-currency lookup is answered in a few milliseconds. To shave the first visit further, add <link rel="preconnect" href="https://ipaddress.to" crossorigin> to your <head>.
Errors
The script does not throw into your page and writes nothing to the console. Failures reach you through the rejected promise, the ipaddressto:error event and the ipa-failed class.
Storage
The answer is kept in the visitor’s own sessionStorage (or localStorage if you choose it) under keys starting ipa:v1:. No cookies are set. If storage is blocked, the script still works and simply asks again on the next page.
Browsers
Anything with fetch and Promise, which is every browser released since 2017. Older ones keep the fallback text.
Versioning
/embed/v1/ will keep working as documented here. Fixes are published to the same address and reach browsers within a few hours. Incompatible changes would ship as /embed/v2/. Because the file can receive fixes, do not pin it with a Subresource Integrity hash.
Content Security Policy
If your site sends one, allow https://ipaddress.to in both script-src and connect-src.
Accuracy
Country is right about 97 times in 100; city is an estimate. We measured both and published the results. Always let the visitor change what you guessed.
Privacy. The lookup is made from the visitor’s browser to our API, so we receive their IP address and the address of the page that asked, as any server they contact would. We log those for operations and abuse prevention and blank the IP after 90 days (privacy policy). We set no cookies and do not track visitors across sites. If your privacy notice lists the services your pages contact, add this one.

Credit

The embed is free and a link back is not required. If it is useful to you, a small credit in your footer or on your about page helps other people find the service, and we are grateful for it.

HTML
<a href="https://ipaddress.to/">IP geolocation by IPAddress.to</a>

Running this on a busy site? Tell us. We would rather make room for your traffic than be surprised by it, and we can let you know before anything changes.