Skip to content

JavaScript SDK

Optional. fetch works fine. The SDK adds caching, request deduplication and typed errors in 738 bytes gzipped, with no dependencies.

Script tag

<script src="https://cdn.instantgeo.info/v1/instantgeo.min.js"></script>
<script>
instantgeo('ig_pk_yourkey').then((geo) => {
console.log(geo.country, geo.city);
});
</script>

npm

Terminal window
npm install @instantgeo/sdk
import { instantgeo } from '@instantgeo/sdk';
const geo = await instantgeo('ig_pk_yourkey');

What it does for you

Caches in sessionStorage. Repeated calls in a tab return with no network request. This is the main reason to use it.

Deduplicates concurrent calls. Three components asking during the same paint produce one request, not three.

Puts the key in the query string, keeping the request a CORS simple request so the browser skips the preflight — saving a full round trip per uncached call.

Aborts hung requests after 8 seconds instead of leaving a promise pending forever.

Degrades when storage is unavailable. Private browsing or a full quota gives you a live request, not an exception.

Options

await instantgeo('ig_pk_yourkey', {
fields: ['country', 'timezone'], // trim the payload
cache: false, // force a fresh lookup
timeout: 3000, // ms, default 8000
endpoint: '', // override for testing
});

Errors

import { instantgeo, GeoError } from '@instantgeo/sdk';
try {
const geo = await instantgeo('ig_pk_yourkey');
} catch (err) {
if (err instanceof GeoError) {
if (err.code === 'quota_exceeded') useDefaults();
else if (err.code === 'origin_not_allowed') console.error(err.message);
}
}

err.message is the server’s message, which is written to be actionable — see the error reference.

Failed requests are never cached, so a later call retries properly.

Always have a fallback

Geolocation should enhance a page, never gate it. Networks fail, VPNs lie, and some visitors cannot be placed at all:

instantgeo('ig_pk_yourkey')
.then((geo) => applyRegion(geo.country ?? 'US'))
.catch(() => applyRegion('US'));