Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

@ipregistry/client

ipregistry15.9kApache-2.06.0.0TypeScript support: included

Official Ipregistry Javascript Library.

country, currency, es5, esm, ip, ip2location, ipaddress, ipdata, ipinfo, ip intelligence, ipinfodb, ipgeo, ip geolocation, ipregistry, ipthreat, ipv4, ipv6, maxmind, nodejs, threat-data, typescript

readme

Ipregistry

Ipregistry Javascript Client Library

License Actions Status npm tsdoc

This is the official Javascript client library for the Ipregistry IP geolocation and threat data API, allowing you to lookup your own IP address or specified ones. Responses return multiple data points including carrier, company, currency, location, timezone, threat information, and more.

Getting Started

You'll need an Ipregistry API key, which you can get along with 100,000 free lookups by signing up for a free account at https://ipregistry.co.

Installation

$ npm install @ipregistry/client

First example

This is a very simple example. This creates a Ipregistry client and retrieves IP info for a given IP address:

const {IpregistryClient} = require('@ipregistry/client');

const client = new IpregistryClient('YOUR_API_KEY');

client.lookupIp('73.2.2.2').then(response => {
    console.log(response.data);
}).catch(error => {
    console.error(error);
})

Instead of using promises, you can also use async/await:

const {IpregistryClient} = require('@ipregistry/client');

const client = new IpregistryClient('YOUR_API_KEY');

async function lookupIpInfo(ip) {
    try {
        const response = await client.lookupIp('73.2.2.2');
        // Get location, threat data and more
        console.log(response.data.location.country.code);
        console.log(response.data.currency.code);
        console.log(response.data.security.is_threat);
    } catch(error) {
        console.error(error);
    }
}

lookupIpInfo();

Or with TypeScript:

import {ApiError, ApiResponse, ClientError, IpInfo, IpregistryClient} from '@ipregistry/client';

async function main() {
    const client: IpregistryClient = new IpregistryClient('tryout')

    try {
        const response: ApiResponse<IpInfo> =
            await client.lookupIp('73.2.2.7')

        // Get location, threat data and more
        console.log(response.data.location.country.code)
        console.log(response.data.currency.code)
        console.log(response.data.security.is_threat)
    } catch (error) {
        if (error instanceof ApiError) {
            // Handle API error here (e.g. Invalid API key or IP address)
            console.error('API error', error)
        } else if (error instanceof ClientError) {
            // Handle client error here (e.g. request timeout)
            console.error('Client error', error)
        } else {
            // Handle unexpected error here
            console.error('Unexpected error', error)
        }
    }
}

main().then(() => 0).catch(() => 1);

Browser support:

<script src="https://unpkg.com/@ipregistry/client/dist/browser/index.js"></script>
<script>
    const client = new ipregistry.IpregistryClient('YOUR_API_KEY');

    client.lookupIp('73.2.2.2').then(response => {
        console.log(response.data);
    }).catch(error => {
        console.error(error);
    });
</script>

More samples are available in the samples folder.

Caching

The Ipregistry client library has built-in support for in-memory caching. By default caching is disabled. Below are examples to enable and configure a caching strategy. Once enabled, the default cache implementation memoizes for 10min the most 2048 recently used lookups on server side (16 when used in a browser).

Make sure you do not create an Ipregistry client per request, otherwise caching will have no effect. In the case you are using a Function-as-a-Service (e.g. AWS Lambda, Firebase Function, Google Cloud Function), then you should declare an Ipregistry client variable in global scope. This way, the Ipregistry client states can be reused in subsequent invocations.

Enabling caching

Caching up to 16384 entries:

const client = new IpregistryClient('YOUR_API_KEY', new InMemoryCache(16384));

Configuring cache max age

Caching up to 16384 entries for at most 6 hours:

const client = new IpregistryClient('YOUR_API_KEY', new InMemoryCache(16384, 3600 * 6 * 1000));

If your purpose is to re-use a same Ipregistry client instance (and thus share the same cache) for different API keys, then you can alter the current configuration to set the API key to use before each request:

client.config.apiKey = 'YOUR_NEW_API_KEY';

Disabling caching

const client = new IpregistryClient('YOUR_API_KEY', new NoCache());

Enabling hostname lookup

By default, the Ipregistry API does not return information about the hostname a given IP address resolves to. In order to include the hostname value in your API result, you need to enable the feature explicitly:

const ipInfo = await client.lookupIp('73.2.2.2', IpregistryOptions.hostname(true));

Errors

All Ipregistry errors inherit IpregistryError class.

Main subtypes are ApiError and ClientError.

Errors of type ApiError include a code field that maps to the one described in the Ipregistry documentation.

Filtering bots

You might want to prevent Ipregistry API requests for crawlers or bots browsing your pages.

A manner to proceed is to identify bots using User-Agents header. To ease this process, the library includes a utility function:

UserAgents.isBot('TO_REPLACE_BY_USER_AGENT_RETRIEVED_FROM_REQUEST_HEADER')

Please note that when caching is disabled, some of the fields above may be null when the content is retrieved from the cache and no request is made to the Ipregistry API.

Selecting fields

To save bandwidth and speed up response times, the API allows selecting fields to return:

const response = await client.lookupIp('73.2.2.2', IpregistryOptions.filter('hostname,location.country.name'));

Usage data

Looking to know the number of credits a request consumed? how much is remaining? or simply get throttling info about an API key for which you have enabled rate limiting?

All client responses are of type ApiResponse and include data about credits and throttling.

const response = await client.lookupIp('73.2.2.2');
console.log(response.credits.consumed);
console.log(response.credits.remaining);
console.log(response.throttling.limit);
console.log(response.throttling.remaining);
console.log(response.throttling.reset);

European Union base URL

For clients operating within the European Union or for those who prefer to route their requests through our EU servers, the Ipregistry client library provides an easy way to configure this preference using the withEuBaseURL option. This ensures that your requests are handled by our EU-based infrastructure, potentially reducing latency and aligning with local data handling regulations:

const config = new IpregistryConfigBuilder('tryout').withEuBaseUrl().build()
const client = new IpregistryClient(config)

Other Libraries

There are official Ipregistry client libraries available for many languages including Java, Python, and more.

Are you looking for an official client with a programming language or framework we do not support yet? let us know.

changelog

Changelog

All notable changes to this project are documented in this file.

The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.

Unreleased

6.0.0

Changed

  • Modify the library packaging to make ECMAScript modules (ESM) optional.
  • Substitute the 'ky' dependency with native fetch API.
  • Reduce the default timeout setting to 5 seconds.
  • Implement retries, up to two times, with exponential backoff in the event of a timeout.

5.0.2 - 2024-03-27

Added

  • Add missing fields size and status to type AutonomousSystemPrefix.

5.0.1 - 2024-03-17

Fixed

  • Fix a packaging issue.

5.0.0 - 2024-03-17

Added

  • New IpregistryClient#batchLookupAsns method.
  • New IpregistryClient#lookupAsn method.
  • New IpregistryClient#originLookupAsn method.
  • New IpregistryConfigBuilder.withEuBaseUrl method. Once configured, requests will be handled by nodes deployed in the European Union only.
  • New IpregistryRequestHandler#batchLookupAsns method.
  • New IpregistryRequestHandler#lookupAsn method.
  • New IpregistryRequestHandler#originLookupAsn method.

    Changed

  • Rename IpregistryClient#batchLookup to IpregistryClient#batchLookupIps.
  • Rename IpregistryClient#lookup to IpregistryClient#lookupIp.
  • Rename IpregistryClient#originLookup to IpregistryClient#originLookupIp.
  • Rename IpregistryClient#parse to IpregistryClient#parseUserAgents.
  • Rename IpregistryConfigBuilder.withApiUrl to IpregistryConfigBuilder.withBaseUrl.
  • Rename IpregistryRequestHandler#batchLookup to IpregistryRequestHandler#batchLookupIps.
  • Rename IpregistryRequestHandler#lookup to IpregistryRequestHandler#lookupIp.
  • Rename IpregistryRequestHandler#originLookup to IpregistryRequestHandler#originLookupIp.
  • Rename IpregistryRequestHandler#parse to IpregistryRequestHandler#parseUserAgents.
  • Rename utility class UserAgent to UserAgents.
  • Replace Axios by ky to bring support to Cloudflare Workers in addition to browser and NodeJS environments.
  • Require NodeJS 18+.

    Fixed

  • Fixed origin requests returning wrong information when caching is enabled. Cache is now automatically disabled for origin requests since it is incompatible.

4.5.0 - 2022-04-15

Added

  • New is_vpn field in security object.

4.4.2 - 2022-04-03

Fixed

  • Invalid field name security.is_tor_exit_node has been renamed to security.is_tor_exit.

    Changed

  • Upgrade dependencies.

4.4.1 - 2022-02-14

  • Upgrade dependencies.

4.4.0 - 2021-12-21

Added

  • New security.is_relay field.

4.3.0 - 2021-12-14

Added

  • New parse method in IpregistryClient for parsing user-agent header values.

    Deprecated

  • Deprecate IpregistryConfigBuilder.withApiUrl in favor of IpregistryConfigBuilder.withBaseUrl.

    Fixed

  • Replace invalid operating_system field in UserAgent by os.

4.2.0 - 2021-10-26

Added

  • IpInfo responses have a new company field.
  • The Connection type field includes a new value of INACTIVE.

4.1.0 - 2021-07-26

Added

  • New connection type government.

    Changed

  • Improve utility function to detect bots/crawlers/spiders based on user-agent value.

    Fixed

  • Fix invalid property names: language.name_native -> language.native and time_zone.daylight_saving -> time_zone.in_daylight_saving.

    Removed

  • Merge connection type cdn with hosting.

4.0.0 - 2021-04-08

Changed

  • [BREAKING] Rename DefaultCache to InMemoryCache.
  • Upgrade dependencies.

3.1.0 - 2020-12-02

Changed

  • Use Authorization header instead of the key query parameter to pass API keys.

3.0.2 - 2020-10-28

Changed

3.0.1 - 2020-10-03

Fixed

  • Access to remaining credits was always returning null due to a packaging issue.

3.0.0 - 2020-06-27

Changed

  • Caching is now optional and disabled by default.
  • Default timeout value has been increased to 15s from 3s.

2.0.1 - 2020-10-03

Fixed

  • Fix access to remaining credits due to the removal of the response header ipregistry-credits from the Ipregistry API.

2.0.0 - 2020-03-12

Changed

  • [BREAKING] All client methods use a new ApiResponse type as response. You can now access usage data (i.e. remaining credits, throttling info) in addition to IP payloads.

1.4.0 - 2020-01-12

Added

  • New field connection.route in response model.
  • Introduce new value cdn for field connection.type.

    Fixed

  • Define a null union type for all fields that can have a null value.

1.3.0 - 2019-10-27

Added

1.2.1 - 2019-10-08

Fixed

  • Fix a packaging issue.

1.2.0 - 2019-10-08

Added

  • Add examples for cache configuration, hostname lookup and fields selection.
  • Add BAD_REQUEST and FORBIDDEN_IP_ORIGIN error codes.

    Changed

  • Export ipregistry as default export in client side module.

1.1.0 - 2019-08-08

Added

  • License headers.
  • Types for new fields returned by the Ipregistry API.

1.0.0 - 2019-07-24

Changed

  • All custom errors extend IpregistryError.

    Fixed

  • Ignore case when checking if User-Agent is spider/bot.

0.10.1 - 2019-07-24

  • Fix deployment to NPM. No code change.

0.10.0 - 2019-07-24

Changed

  • Rename browser file to index.js from index.browser.js.

0.9.2 - 2019-07-24

Added

  • Browser support.

0.9.1 - 2019-07-23

  • First public release.