Skip to content

IP-Sonar JavaScript SDK

The IP-Sonar JavaScript SDK provides a modern, TypeScript-first interface for the IP-Sonar geolocation API. Get detailed location information for any IP address with just a few lines of code.

  • TypeScript Support - Fully typed API with IntelliSense support
  • Browser & Node.js - Works in both environments
  • Batch Processing - Look up multiple IPs in a single request
  • Configurable - Flexible configuration options
  • Error Handling - Comprehensive error handling with detailed messages
  • Lightweight - Minimal dependencies, optimized bundle size
Terminal window
npm install @ip-sonar/ip-sonar-js
Terminal window
yarn add @ip-sonar/ip-sonar-js
<script type="module">
import { createClient } from 'https://unpkg.com/@ip-sonar/ip-sonar-js/dist/index.esm.js';
</script>
import { createClient } from '@ip-sonar/ip-sonar-js';
// Create client (no API key required for basic usage)
const client = createClient();
// Look up your own IP
const myInfo = await client.lookupMyIP();
console.log(`You're in ${myInfo.city_name}, ${myInfo.country_name}`);
// Look up a specific IP
const ipInfo = await client.lookupIP('8.8.8.8');
console.log(`IP location: ${ipInfo.country_name}`);
import { createClient } from '@ip-sonar/ip-sonar-js';
const client = createClient({
apiKey: 'your-api-key-here'
});
const result = await client.lookupIP('216.8.112.107');

The SDK accepts various configuration options:

import { IPSonarClient } from '@ip-sonar/ip-sonar-js';
const client = new IPSonarClient({
// API key for authentication (optional)
apiKey: 'your-api-key',
// Default parameters for all requests (optional)
defaultParams: {
locale_code: 'en',
fields: 'country_name,city_name,timezone'
},
// Request timeout in milliseconds (default: 10000)
timeout: 15000
});
OptionTypeDefaultDescription
apiKeystringundefinedYour IP-Sonar API key
baseUrlstring'https://api.ip-sonar.com'API base URL
defaultParamsLookupParamsundefinedDefault parameters for all requests
timeoutnumber10000Request timeout in milliseconds

Retrieves geolocation information for the client’s IP address.

const myInfo = await client.lookupMyIP();
console.log(myInfo.country_name); // "United States"

Parameters:

  • options (optional): RequestOptions

Returns: Promise<LookupIPResponse>

Retrieves geolocation information for a specific IP address.

const ipInfo = await client.lookupIP('216.8.112.107');
console.log(ipInfo.city_name); // "Cleveland"

Parameters:

  • ip: string - The IP address to look up
  • options (optional): RequestOptions

Returns: Promise<LookupIPResponse>

Retrieves geolocation information for multiple IP addresses in a single request.

const results = await client.batchLookup(['215.8.112.107', '216.8.112.107']);
results.data.forEach(result => {
console.log(`${result.ip}: ${result.country_name}`);
});

Parameters:

  • ips: string[] - Array of IP addresses (1-100 items)
  • options (optional): RequestOptions

Returns: Promise<BatchLookupIPResponse>

You can override default parameters for individual requests:

// Get only specific fields for this request
const result = await client.lookupIP('216.8.112.107', {
params: {
fields: 'country_name,timezone',
locale_code: 'es'
},
timeout: 5000
});

Specify which fields to include in the response:

const result = await client.lookupIP('216.8.112.107', {
params: {
fields: 'country_name,city_name,timezone,latitude,longitude'
}
});

Available fields:

  • ip - IP address
  • latitude - Latitude coordinate
  • longitude - Longitude coordinate
  • postal_code - Postal/ZIP code
  • accuracy_radius - Accuracy radius in kilometers
  • continent_code - Continent code (AF, AN, AS, EU, NA, OC, SA)
  • continent_name - Continent name
  • country_code - ISO 3166-1 country code
  • country_name - Country name
  • subdivision_1_code - First subdivision code (state/province)
  • subdivision_1_name - First subdivision name
  • subdivision_2_code - Second subdivision code
  • subdivision_2_name - Second subdivision name
  • city_name - City name
  • timezone - IANA timezone
  • is_in_eu - Whether the country is in the EU

Get location names in different languages:

// Get results in Spanish
const result = await client.lookupIP('8.8.8.8', {
params: { locale_code: 'es' }
});

Supported locales:

  • de - German
  • en - English (default)
  • es - Spanish
  • fr - French
  • ja - Japanese
  • pt-br - Portuguese (Brazil)
  • ru - Russian
  • zh-cn - Chinese (Simplified)
interface LookupIPResponse {
ip?: string;
latitude?: number;
longitude?: number;
postal_code?: string;
accuracy_radius?: number;
continent_code?: 'AF' | 'AN' | 'AS' | 'EU' | 'NA' | 'OC' | 'SA';
continent_name?: string;
country_code?: string;
country_name?: string;
subdivision_1_code?: string;
subdivision_1_name?: string;
subdivision_2_code?: string;
subdivision_2_name?: string;
city_name?: string;
timezone?: string;
is_in_eu?: boolean;
}
interface BatchLookupIPResponse {
data: LookupIPResponse[];
}
{
"accuracy_radius": 50,
"city_name": "Cleveland",
"continent_code": "NA",
"continent_name": "North America",
"country_code": "US",
"country_name": "United States",
"ip": "216.8.112.107",
"is_in_eu": false,
"latitude": 41.4377,
"longitude": -81.5487,
"postal_code": "44128",
"subdivision_1_code": "OH",
"subdivision_1_name": "Ohio",
"timezone": "America/New_York"
}

The SDK provides comprehensive error handling with typed error objects:

import { createClient } from '@ip-sonar/ip-sonar-js';
const client = createClient();
try {
const result = await client.lookupIP('invalid-ip');
} catch (error) {
if (error.status) {
console.error(`API Error ${error.status}: ${error.apiMessage || error.message}`);
} else {
console.error(`Network Error: ${error.message}`);
}
}
interface APIError extends Error {
status?: number; // HTTP status code
body?: unknown; // Response body
apiMessage?: string; // API error message
}
  • 400 Bad Request: Invalid IP address or parameters
  • 401 Unauthorized: Invalid or missing API key
  • 429 Too Many Requests: Rate limit exceeded
  • 500 Internal Server Error: API server error
  • Network Error: Connection issues
  • Timeout Error: Request timeout
import { IPSonarClient } from '@ip-sonar/ip-sonar-js';
// Advanced configuration
const client = new IPSonarClient({
apiKey: process.env.IP_SONAR_API_KEY,
timeout: 30000,
defaultParams: {
locale_code: 'en',
fields: 'country_name,city_name,timezone,latitude,longitude'
}
});
async function processIPBatch(ips: string[]) {
try {
const results = await client.batchLookup(ips);
return results.data.map(result => ({
ip: result.ip,
location: `${result.city_name}, ${result.country_name}`,
timezone: result.timezone
}));
} catch (error) {
console.error('Batch lookup failed:', error.message);
throw error;
}
}
// Usage
const locations = await processIPBatch([
'216.7.112.107',
'216.8.112.107'
]);
import { createClient } from '@ip-sonar/ip-sonar-js';
const client = createClient({
apiKey: process.env.IP_SONAR_API_KEY
});
// Server-side IP lookup
app.get('/location/:ip', async (req, res) => {
try {
const result = await client.lookupIP(req.params.ip);
res.json(result);
} catch (error) {
res.status(error.status || 500).json({ error: error.message });
}
});
<!DOCTYPE html>
<html>
<head>
<title>IP Location Demo</title>
</head>
<body>
<div id="location"></div>
<script type="module">
import { createClient } from 'https://unpkg.com/@ip-sonar/ip-sonar-js/dist/index.esm.js';
const client = createClient();
client.lookupMyIP()
.then(result => {
document.getElementById('location').innerHTML =
`You're in ${result.city_name}, ${result.country_name}`;
})
.catch(error => {
console.error('Error:', error.message);
});
</script>
</body>
</html>

The SDK is written in TypeScript and provides full type definitions:

import {
createClient,
IPSonarClient,
IPGeolocation,
LookupIPResponse,
BatchLookupIPResponse,
APIError
} from '@ip-sonar/ip-sonar-js';
// All types are available for import
const client: IPSonarClient = createClient();
const result: LookupIPResponse = await client.lookupMyIP();

No breaking changes. All existing code will continue to work.

If you’re migrating from another IP geolocation library:

// Before (example with another library)
const response = await fetch(`https://api.example.com/ip/${ip}`);
const data = await response.json();
// After (with IP-Sonar SDK)
const client = createClient();
const data = await client.lookupIP(ip);

MIT.