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.
Features
Section titled “Features”- 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
Installation
Section titled “Installation”npm install @ip-sonar/ip-sonar-js
yarn add @ip-sonar/ip-sonar-js
CDN (Browser)
Section titled “CDN (Browser)”<script type="module"> import { createClient } from 'https://unpkg.com/@ip-sonar/ip-sonar-js/dist/index.esm.js';</script>
Quick Start
Section titled “Quick Start”Basic Usage
Section titled “Basic Usage”import { createClient } from '@ip-sonar/ip-sonar-js';
// Create client (no API key required for basic usage)const client = createClient();
// Look up your own IPconst myInfo = await client.lookupMyIP();console.log(`You're in ${myInfo.city_name}, ${myInfo.country_name}`);
// Look up a specific IPconst ipInfo = await client.lookupIP('8.8.8.8');console.log(`IP location: ${ipInfo.country_name}`);
With API Key
Section titled “With API Key”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');
Configuration
Section titled “Configuration”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});
Configuration Options
Section titled “Configuration Options”Option | Type | Default | Description |
---|---|---|---|
apiKey | string | undefined | Your IP-Sonar API key |
baseUrl | string | 'https://api.ip-sonar.com' | API base URL |
defaultParams | LookupParams | undefined | Default parameters for all requests |
timeout | number | 10000 | Request timeout in milliseconds |
API Reference
Section titled “API Reference”Client Methods
Section titled “Client Methods”lookupMyIP(options?)
Section titled “lookupMyIP(options?)”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>
lookupIP(ip, options?)
Section titled “lookupIP(ip, options?)”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 upoptions
(optional):RequestOptions
Returns: Promise<LookupIPResponse>
batchLookup(ips, options?)
Section titled “batchLookup(ips, options?)”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>
Request Options
Section titled “Request Options”You can override default parameters for individual requests:
// Get only specific fields for this requestconst result = await client.lookupIP('216.8.112.107', { params: { fields: 'country_name,timezone', locale_code: 'es' }, timeout: 5000});
Query Parameters
Section titled “Query Parameters”fields
Section titled “fields”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 addresslatitude
- Latitude coordinatelongitude
- Longitude coordinatepostal_code
- Postal/ZIP codeaccuracy_radius
- Accuracy radius in kilometerscontinent_code
- Continent code (AF, AN, AS, EU, NA, OC, SA)continent_name
- Continent namecountry_code
- ISO 3166-1 country codecountry_name
- Country namesubdivision_1_code
- First subdivision code (state/province)subdivision_1_name
- First subdivision namesubdivision_2_code
- Second subdivision codesubdivision_2_name
- Second subdivision namecity_name
- City nametimezone
- IANA timezoneis_in_eu
- Whether the country is in the EU
locale_code
Section titled “locale_code”Get location names in different languages:
// Get results in Spanishconst result = await client.lookupIP('8.8.8.8', { params: { locale_code: 'es' }});
Supported locales:
de
- Germanen
- English (default)es
- Spanishfr
- Frenchja
- Japanesept-br
- Portuguese (Brazil)ru
- Russianzh-cn
- Chinese (Simplified)
Response Format
Section titled “Response Format”Single IP Lookup Response
Section titled “Single IP Lookup Response”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;}
Batch Lookup Response
Section titled “Batch Lookup Response”interface BatchLookupIPResponse { data: LookupIPResponse[];}
Example Response
Section titled “Example Response”{ "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"}
Error Handling
Section titled “Error Handling”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}`); }}
Error Types
Section titled “Error Types”APIError
Section titled “APIError”interface APIError extends Error { status?: number; // HTTP status code body?: unknown; // Response body apiMessage?: string; // API error message}
Common Error Scenarios
Section titled “Common Error Scenarios”- 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
Advanced Usage
Section titled “Advanced Usage”Custom Headers and Configuration
Section titled “Custom Headers and Configuration”import { IPSonarClient } from '@ip-sonar/ip-sonar-js';
// Advanced configurationconst client = new IPSonarClient({ apiKey: process.env.IP_SONAR_API_KEY, timeout: 30000, defaultParams: { locale_code: 'en', fields: 'country_name,city_name,timezone,latitude,longitude' }});
Batch Processing with Error Handling
Section titled “Batch Processing with Error Handling”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; }}
// Usageconst locations = await processIPBatch([ '216.7.112.107', '216.8.112.107']);
Environment-Specific Usage
Section titled “Environment-Specific Usage”Node.js
Section titled “Node.js”import { createClient } from '@ip-sonar/ip-sonar-js';
const client = createClient({ apiKey: process.env.IP_SONAR_API_KEY});
// Server-side IP lookupapp.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 }); }});
Browser
Section titled “Browser”<!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>
TypeScript Support
Section titled “TypeScript Support”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 importconst client: IPSonarClient = createClient();const result: LookupIPResponse = await client.lookupMyIP();
Migration Guide
Section titled “Migration Guide”From Version 1.0.0 to 1.0.2
Section titled “From Version 1.0.0 to 1.0.2”No breaking changes. All existing code will continue to work.
From Other Libraries
Section titled “From Other Libraries”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);
Support
Section titled “Support”License
Section titled “License”MIT.