Skip to content

Repository files navigation

IPGeolocation JavaScript SDK

Official JavaScript SDK for the IPGeolocation IP Location API.

Look up IPv4, IPv6, and domains with /v3/ipgeo and /v3/ipgeo-bulk. Get geolocation, company, ASN, timezone, network, hostname, abuse, user-agent, and security data from one API. Includes ESM, CommonJS, and TypeScript declarations.

Works in Node.js 18+ and in other runtimes that already provide fetch.

Table of Contents

Installation

npm install ip-geolocation-api-javascript-sdk

ES Modules

import{IpGeolocationClient}from"ip-geolocation-api-javascript-sdk";

CommonJS

const{ IpGeolocationClient }=require("ip-geolocation-api-javascript-sdk");

Quick Start

import{IpGeolocationClient}from"ip-geolocation-api-javascript-sdk";asyncfunctionmain(){constclient=newIpGeolocationClient({apiKey: process.env.IPGEO_API_KEY,});try{constresponse=awaitclient.lookupIpGeolocation({ip: "8.8.8.8",});console.log("IP:",response.data.ip);// "8.8.8.8"console.log("Country:",response.data.location?.countryName);// "United States"console.log("City:",response.data.location?.city);console.log("Timezone:",response.data.timeZone?.name);console.log("Credits charged:",response.metadata.creditsCharged);}finally{awaitclient.close();}}main().catch((error)=>{console.error(error);});

You can pass plain objects to request methods. If you want validation before the request is sent, use LookupIpGeolocationRequest and BulkLookupIpGeolocationRequest.

At a Glance

ItemValue
Packageip-geolocation-api-javascript-sdk
API TypeIPGeolocation IP Location API
Supported Endpoints/v3/ipgeo, /v3/ipgeo-bulk
Supported InputsIPv4, IPv6, domain
Main Data ReturnedGeolocation, company, ASN, timezone, network, security, abuse, hostname, user-agent, currency
AuthenticationAPI key, request-origin auth for /v3/ipgeo only
Response FormatsStructured JSON, raw JSON, raw XML
Bulk LimitUp to 50,000 IPs or domains per request
RuntimeNode.js 18+ or any runtime with fetch

Get Your API Key

To use most SDK features, create or access your IPGeolocation account and copy an API key from your dashboard.

  1. Sign up: https://app.ipgeolocation.io/signup
  2. Verify your email if prompted
  3. Sign in: https://app.ipgeolocation.io/login
  4. Open your dashboard: https://app.ipgeolocation.io/dashboard
  5. Copy an API key from the API Keys section
  6. Pass it to new IpGeolocationClient({ apiKey: "YOUR_API_KEY" })

For server-side code, keep the API key in an environment variable or secret manager. For browser-based single lookups on paid plans, use request-origin auth instead of exposing an API key in frontend code.

What You Can Get From One API Call

Data SetHow To Request ItCommon Use Cases
IP geolocationDefault responseIP lookup, localization, geo targeting
Company and ASNDefault responseISP lookup, ownership enrichment, network analysis
TimezoneDefault responseLocal time lookup, scheduling, regional reporting
Network and currencyDefault responseRouting context, analytics, pricing flows
Security and risk signalsinclude: ["security"]VPN detection, proxy detection, fraud prevention, threat analysis
Abuse contact datainclude: ["abuse"]Incident response, abuse handling, reporting
Hostname datainclude: ["hostname"], ["liveHostname"], ["hostnameFallbackLive"]Reverse DNS lookup, infrastructure enrichment, hosting checks
User-agent datainclude: ["user_agent"] with userAgent or a User-Agent headerBrowser detection, device detection, traffic analysis
Geo accuracy and DMA datainclude: ["geo_accuracy"], ["dma_code"]Local targeting, media market mapping, proximity analysis

Security and Risk Signals

Request include: ["security"] when you need the security object in the response.

Use CaseSDK Fields
VPN detectionsecurity.isVpn, security.vpnProviderNames, security.vpnConfidenceScore, security.vpnLastSeen
Proxy detectionsecurity.isProxy, security.proxyProviderNames, security.proxyConfidenceScore, security.proxyLastSeen
Residential proxy detectionsecurity.isResidentialProxy
Tor detectionsecurity.isTor
Anonymous IP detectionsecurity.isAnonymous
Threat score and risk scoringsecurity.threatScore
Bot, spam, and attacker signalssecurity.isBot, security.isSpam, security.isKnownAttacker
Relay detectionsecurity.isRelay, security.relayProviderName
Cloud, hosting, or data center IP detectionsecurity.isCloudProvider, security.cloudProviderName

Provider names, confidence scores, and last-seen dates appear when the API has that data.

Supported Endpoints

EndpointHTTP MethodSDK MethodsPrimary Use Case
/v3/ipgeoGETlookupIpGeolocation(...), lookupIpGeolocationRaw(...)Single IPv4, IPv6, or domain lookup
/v3/ipgeo-bulkPOSTbulkLookupIpGeolocation(...), bulkLookupIpGeolocationRaw(...)Bulk lookup for up to 50,000 IPs or domains

These two endpoints can return geolocation, company, ASN, timezone, network, currency, hostname, abuse, user-agent, and security data depending on your request and plan.

Authentication Modes

ModeSDK SetupTypical Use
API key query paramnew IpGeolocationClient({ apiKey: "YOUR_API_KEY" })Server-side API calls, jobs, bulk lookups
Request-origin authnew IpGeolocationClient({ requestOrigin: "https://app.example.com" })Browser-based single lookups on paid plans

Important

Request-origin auth does not work with /v3/ipgeo-bulk. Bulk lookup always requires apiKey.

Note

If you set both apiKey and requestOrigin, single lookup still uses the API key. The API key is sent as the apiKey query parameter, so avoid logging full request URLs.

Plan Features and Limits

Feature availability depends on your plan and request parameters.

CapabilityFree PlanPaid Plan
IPv4 and IPv6 single lookupSupportedSupported
Domain lookupNot supportedSupported
Bulk endpoint /v3/ipgeo-bulkNot supportedSupported, but always requires an API key
include: ["*"]Accepted, returns the default response onlyAccepted, returns all available modules
include: ["security"], ["abuse"], ["hostname"], ["liveHostname"], ["hostnameFallbackLive"], ["geo_accuracy"], ["dma_code"], ["user_agent"]Not supportedSupported
Non-English langNot supportedSupported
fields and excludesSupportedSupported
Request-origin authNot supportedSupported for /v3/ipgeo only

Paid plans still need include for optional modules. fields and excludes only trim the response. They do not turn modules on or unlock paid data.

Client Configuration

OptionTypeDefaultNotes
apiKeystringunsetRequired for bulk lookup. Optional for single lookup if requestOrigin is set.
requestOriginstringunsetMust be an absolute http or https origin. No path, query string, fragment, or userinfo.
baseUrlstringhttps://api.ipgeolocation.ioOverride the API base URL. Must be an absolute http or https URL.
connectTimeoutMsnumber10000Time to wait for response headers. Must be a positive integer.
readTimeoutMsnumber30000Time to wait while reading the response body. Must be a positive integer.

You can also pass a custom HttpTransport as the second constructor argument.

Available Methods

MethodReturnsNotes
lookupIpGeolocation(request)Promise<ApiResponse<IpGeolocationResponse>>Single lookup. Typed JSON response.
lookupIpGeolocationRaw(request)Promise<ApiResponse<string>>Single lookup. Raw JSON or XML string.
bulkLookupIpGeolocation(request)Promise<ApiResponse<readonly BulkLookupResult[]>>Bulk lookup. Typed JSON response.
bulkLookupIpGeolocationRaw(request)Promise<ApiResponse<string>>Bulk lookup. Raw JSON or XML string.
close()Promise<void>Closes the client. Do not reuse the client after this.

Note

Typed methods support JSON only. Use the raw methods when you need XML output.

Request Options

OptionApplies ToNotes
ipSingle lookupIPv4, IPv6, or domain. Omit it for caller IP lookup. Domain lookup requires a paid plan.
ipsBulk lookupIterable of 1 to 50,000 IPs or domains.
langSingle and bulkOne of en, de, ru, ja, fr, cn, es, cs, it, ko, fa, pt.
includeSingle and bulkIterable of module names such as security, abuse, user_agent, hostname, liveHostname, hostnameFallbackLive, geo_accuracy, dma_code, or *.
fieldsSingle and bulkIterable of field paths to keep, for example ["location.country_name", "security.threat_score"].
excludesSingle and bulkIterable of field paths to remove from the response.
userAgentSingle and bulkOverrides the outbound User-Agent header. If you also pass a User-Agent header in headers, userAgent wins.
headersSingle and bulkExtra request headers. Use a plain object, Headers, Map, or iterable of [name, value] pairs.
outputSingle and bulk"json" or "xml". Typed methods require JSON.

Single Lookup Examples

The examples below assume you already have a configured client and are running inside an async function or an ESM module with top-level await:

import{IpGeolocationClient}from"ip-geolocation-api-javascript-sdk";constclient=newIpGeolocationClient({apiKey: process.env.IPGEO_API_KEY,});

Caller IP

Omit ip to look up the public IP of the machine making the request.

constresponse=awaitclient.lookupIpGeolocation({});console.log(response.data.ip);

Domain Lookup

Domain lookup is a paid-plan feature.

constresponse=awaitclient.lookupIpGeolocation({ip: "ipgeolocation.io",});console.log(response.data.ip);console.log(response.data.domain);// "ipgeolocation.io"console.log(response.data.location?.countryName);

Security and Abuse

constresponse=awaitclient.lookupIpGeolocation({ip: "9.9.9.9",include: ["security","abuse"],});console.log(response.data.security?.threatScore);console.log(response.data.security?.isVpn);console.log(response.data.abuse?.emails?.[0]);

Hostname Variants

constresponse=awaitclient.lookupIpGeolocation({ip: "ipgeolocation.io",include: ["hostname","liveHostname","hostnameFallbackLive"],});console.log(response.data.hostname);

User-Agent Parsing

To parse a visitor user-agent string, request user_agent and pass the visitor string in userAgent.

constresponse=awaitclient.lookupIpGeolocation({ip: "8.8.8.8",include: ["user_agent"],userAgent:
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) "+"AppleWebKit/601.3.9 (KHTML, like Gecko) Version/9.0.2 Safari/601.3.9",});console.log(response.data.userAgent?.name);console.log(response.data.userAgent?.operatingSystem?.name);console.log(response.data.userAgent?.device?.type);

Filtered Response

Use fields to keep only the data you need, or excludes to remove fields from the response.

constresponse=awaitclient.lookupIpGeolocation({ip: "8.8.8.8",include: ["security"],fields: ["location.country_name","security.threat_score","security.is_vpn"],excludes: ["currency"],});console.log(response.data.location?.countryName);console.log(response.data.security?.threatScore);console.log(response.data.security?.isVpn);

Request Classes

If you want request validation before sending the call, create the request explicitly.

import{IpGeolocationClient,LookupIpGeolocationRequest,}from"ip-geolocation-api-javascript-sdk";constclient=newIpGeolocationClient({apiKey: process.env.IPGEO_API_KEY,});constrequest=newLookupIpGeolocationRequest({ip: "8.8.8.8",include: ["security"],});constresponse=awaitclient.lookupIpGeolocation(request);console.log(response.data.security?.isProxy);

Request-Origin Auth

Use this only for paid-plan single lookups from an allowlisted origin.

constbrowserClient=newIpGeolocationClient({requestOrigin: "https://app.example.com",});constresponse=awaitbrowserClient.lookupIpGeolocation({ip: "8.8.8.8",});console.log(response.data.ip);awaitbrowserClient.close();

Raw JSON and XML

Use raw methods when you want the original response body as a string.

import{IpGeolocationClient,ResponseFormat,}from"ip-geolocation-api-javascript-sdk";constclient=newIpGeolocationClient({apiKey: process.env.IPGEO_API_KEY,});constrawJson=awaitclient.lookupIpGeolocationRaw({ip: "8.8.8.8",});console.log(rawJson.data);constrawXml=awaitclient.lookupIpGeolocationRaw({ip: "8.8.8.8",output: ResponseFormat.XML,});console.log(rawXml.data);

Bulk Lookup Examples

Bulk lookup is a paid-plan feature and always requires apiKey.

Basic Bulk Lookup

constresponse=awaitclient.bulkLookupIpGeolocation({ips: ["8.8.8.8","1.1.1.1"],});for(constresultofresponse.data){if(result.success){console.log(result.data.ip,result.data.location?.countryName);// "8.8.8.8", "United States"}}

Mixed Success and Error Results

Each bulk result is either a success with data or an error with error.message.

constresponse=awaitclient.bulkLookupIpGeolocation({ips: ["8.8.8.8","invalid-ip","1.1.1.1"],include: ["security"],});for(constresultofresponse.data){if(result.success){console.log(result.data.ip,result.data.security?.threatScore);continue;}console.error(result.error.message);}

Response Metadata

Every SDK call returns an object with data and metadata.

metadata is an ApiResponseMetadata instance with:

FieldMeaning
statusCodeHTTP status code returned by the API
durationMsEnd-to-end request time measured by the SDK
creditsChargedCredits charged for the request, when returned by the API
successfulRecordsNumber of successful records for bulk lookups, when returned by the API
rawHeadersRaw response headers as a multi-map

It also provides:

  • metadata.headerValues(name)
  • metadata.firstHeaderValue(name)

Example:

constresponse=awaitclient.lookupIpGeolocation({ip: "8.8.8.8",});console.log(response.metadata.statusCode);console.log(response.metadata.durationMs);console.log(response.metadata.firstHeaderValue("x-ratelimit-remaining"));

JSON Helpers

Use toJson() or toPrettyJson() when you want a stable JSON view of SDK objects.

import{toPrettyJson}from"ip-geolocation-api-javascript-sdk";constresponse=awaitclient.lookupIpGeolocation({ip: "8.8.8.8",});console.log(toPrettyJson(response.data));

Error Handling

All SDK errors extend IpGeolocationError.

Runtime and validation errors:

  • ValidationError
  • SerializationError
  • TransportError
  • RequestTimeoutError

API errors:

  • ApiError
  • BadRequestError
  • UnauthorizedError
  • NotFoundError
  • MethodNotAllowedError
  • PayloadTooLargeError
  • UnsupportedMediaTypeError
  • LockedError
  • RateLimitError
  • ClientClosedRequestError
  • ServerError

ApiError and its subclasses expose:

  • statusCode
  • apiMessage

Example:

import{IpGeolocationClient,RateLimitError,UnauthorizedError,}from"ip-geolocation-api-javascript-sdk";constclient=newIpGeolocationClient({apiKey: process.env.IPGEO_API_KEY,});try{constresponse=awaitclient.lookupIpGeolocation({ip: "8.8.8.8",});console.log(response.data.location?.countryName);}catch(error){if(errorinstanceofUnauthorizedError){console.error(error.apiMessage);}elseif(errorinstanceofRateLimitError){console.error("Rate limit reached");}else{throwerror;}}finally{awaitclient.close();}

Troubleshooting

ValidationError: single lookup requires apiKey or requestOrigin in client config

Set either apiKey or requestOrigin when creating the client.

ValidationError: bulk lookup requires apiKey in client config

Bulk lookup always requires apiKey, even if requestOrigin is set.

UnauthorizedError on domain lookup, optional modules, or non-English lang

Those features require a paid plan. Free plans only support the base single-lookup response.

XML output does not work with typed methods

Use lookupIpGeolocationRaw(...) or bulkLookupIpGeolocationRaw(...) with output: "xml".

ValidationError: client is closed

Create a new client after calling close(). Closed clients cannot be reused.

RequestTimeoutError

Increase connectTimeoutMs or readTimeoutMs if your environment needs longer network time.

Frequently Asked Questions

Can I use this SDK in the browser? Yes, if your runtime provides `fetch`. Do not expose `apiKey` in frontend code. For browser single lookups on paid plans, use `requestOrigin`.
Does the SDK retry failed requests? No. Timeouts, rate limits, and server errors are raised directly. Add your own retry policy outside the SDK if you need one.
Can I pass custom headers? Yes. Use `headers` with a plain object, `Headers`, `Map`, or an iterable of `[name, value]` pairs.
Does `userAgent` do the same thing as `headers["User-Agent"]`? Almost. Both affect the outbound `User-Agent` header, but `userAgent` takes precedence when both are set.
Can I use request-origin auth with bulk lookup? No. Bulk lookup always requires `apiKey`.
Do typed methods support XML? No. Typed methods require JSON. Use raw methods if you need XML.

Related Packages

  • TypeScript runtime SDK: ip-geolocation-api-sdk-typescript
  • TypeScript types-only package: ip-geolocation-api-typescript-types

Links

Releases

Packages

Used by

Contributors

Languages