TypeScript Library

The ipflare npm package offers a simple and efficient way to retrieve geolocation information for IP addresses using the IP Flare API. The library provides comprehensive TypeScript support, robust error handling, and advanced features for production applications.

Features

  • Result-based Error Handling: All methods return a Result type with explicit success/failure states
  • IPv4 & IPv6 Support: Comprehensive validation for both IPv4 and IPv6 addresses
  • Type Safety: Full TypeScript support with type guards and discriminated unions
  • Input Validation: Client-side validation prevents invalid requests and provides immediate feedback
  • Structured Error Types: Specific error messages for different scenarios with structured error types
  • Bulk Operations: Process up to 500 IP addresses in a single request
  • Configurable: Custom timeout, base URL, and other configuration options
  • Production Ready: Comprehensive testing (96%+ coverage) and enterprise-grade reliability

Installation

1npm install ipflare

Quick Start

After installing the package, you can use it in your JavaScript or TypeScript projects to fetch geolocation data with comprehensive error handling and type safety. The library uses a Result-based approach that eliminates the need for try-catch blocks.

Initialize the Client

1// ipflare.ts
2
3import { IPFlare } from "ipflare";
4
5// Initialize with your API key (required)
6const geolocator = new IPFlare({
7 apiKey: 'YOUR_API_KEY',
8});

Examples

The library uses a Result-based API that eliminates try-catch blocks and provides structured error handling with explicit success/failure states.

Single IP Lookup

The following example demonstrates IP lookups with automatic validation for both IPv4 and IPv6 addresses and structured error information.

1const result = await geolocator.lookup("178.238.11.6");
2
3if (!result.ok) {
4 // Handle different error types
5 switch (result.error.type) {
6 case 'INVALID_IP_ADDRESS':
7 console.log('Invalid IP:', result.error.message);
8 break;
9 case 'UNAUTHORIZED':
10 console.log('API key issue:', result.error.message);
11 break;
12 case 'QUOTA_EXCEEDED':
13 console.log('Quota exceeded:', result.error.message);
14 break;
15 case 'GEOLOCATION_NOT_FOUND':
16 console.log('No geolocation data:', result.error.message);
17 break;
18 default:
19 console.log('Error:', result.error.message);
20 }
21 return;
22}
23
24// TypeScript knows result.data is IPGeolocationResponse
25console.log('Location:', result.data.city, result.data.country_name);
26console.log('Coordinates:', result.data.latitude, result.data.longitude);

Bulk IP Lookup

Bulk lookup for multiple IP addresses (up to 500 per request) with structured error handling:

1// Bulk lookup
2const bulkResult = await geolocator.bulkLookup({
3 ips: ["178.238.11.6", "1.1.1.1", "2001:4860:4860::8888"],
4 include: {
5 asn: true,
6 isp: true,
7 },
8});
9
10if (!bulkResult.ok) {
11 console.log('Bulk lookup failed:', bulkResult.error.message);
12 return;
13}
14
15// Process results
16for (const item of bulkResult.data) {
17 if (item.status === 'success') {
18 console.log(`${item.data.ip}: ${item.data.city}, ${item.data.country_name}`);
19 if (item.data.asn) console.log(`ASN: ${item.data.asn}`);
20 if (item.data.isp) console.log(`ISP: ${item.data.isp}`);
21 } else {
22 console.log(`${item.ip}: Error - ${item.error_message}`);
23 }
24}

Lookup with Additional Fields

To retrieve additional fields like ASN and ISP information, pass the include options. Visit the Geolocation page for more information about available fields.

1// Lookup with additional fields
2const result = await geolocator.lookup("178.238.11.6", {
3 include: {
4 asn: true,
5 isp: true,
6 },
7});
8
9if (!result.ok) {
10 console.log('Lookup failed:', result.error.message);
11 return;
12}
13
14console.log('IP:', result.data.ip);
15console.log('Location:', result.data.city, result.data.country_name);
16console.log('ASN:', result.data.asn);
17console.log('ISP:', result.data.isp);

Error Handling

The library provides comprehensive error handling with specific error types for different scenarios. No try-catch blocks are needed:

1import { IPFlare } from "ipflare";
2
3const geolocator = new IPFlare({ apiKey: 'your-api-key' });
4
5const result = await geolocator.lookup("8.8.8.8");
6
7if (!result.ok) {
8 // Handle specific error types
9 switch (result.error.type) {
10 case 'INVALID_IP_ADDRESS':
11 console.error('Please provide a valid IP address');
12 break;
13 case 'RESERVED_IP_ADDRESS':
14 console.error('IP address is reserved (private/local)');
15 break;
16 case 'UNAUTHORIZED':
17 console.error('Please check your API key');
18 break;
19 case 'QUOTA_EXCEEDED':
20 console.error('Usage quota exceeded, please upgrade your plan');
21 break;
22 case 'GEOLOCATION_NOT_FOUND':
23 console.error('No geolocation data available for this IP');
24 break;
25 case 'INTERNAL_SERVER_ERROR':
26 console.error('Server error occurred, please try again');
27 break;
28 default:
29 console.error('Unexpected error:', result.error.message);
30 }
31 return;
32}
33
34// Success - TypeScript knows the exact type
35console.log('Success:', result.data);
36
37// Bulk lookup error handling
38const bulkResult = await geolocator.bulkLookup({
39 ips: ["8.8.8.8", "1.1.1.1"]
40});
41
42if (!bulkResult.ok) {
43 console.error('Bulk lookup failed:', bulkResult.error.message);
44 return;
45}
46
47console.log('Bulk results:', bulkResult.data);

Type Guards

The library provides type guard functions to safely work with results and discriminate between successful and error responses:

1import {
2 IPFlare,
3 isSuccess,
4 isError,
5 isIPGeolocationSuccess,
6 isIPGeolocationError
7} from "ipflare";
8
9const geolocator = new IPFlare({ apiKey: 'your-api-key' });
10
11// Result-based API with type guards
12const result = await geolocator.lookup("8.8.8.8");
13
14if (isSuccess(result)) {
15 // TypeScript knows this is a success response
16 console.log('Success:', result.data);
17 console.log('Country:', result.data.country_name);
18 console.log('City:', result.data.city);
19} else if (isError(result)) {
20 // TypeScript knows this is an error response
21 console.error('Error type:', result.error.type);
22 console.error('Error message:', result.error.message);
23}
24
25// Bulk lookup with type guards
26const bulkResult = await geolocator.bulkLookup({
27 ips: ["8.8.8.8", "1.1.1.1"]
28});
29
30if (isSuccess(bulkResult)) {
31 // Process each result in the bulk response
32 for (const item of bulkResult.data) {
33 if (isIPGeolocationSuccess(item)) {
34 console.log(`Success for ${item.ip}:`, item.data);
35 } else if (isIPGeolocationError(item)) {
36 console.error(`Error for ${item.ip}: ${item.error_message}`);
37 }
38 }
39}
40
41// Alternative approach using status property
42if (isSuccess(bulkResult)) {
43 bulkResult.data.forEach(result => {
44 switch (result.status) {
45 case "success":
46 console.log("Success:", result.data);
47 break;
48 case "error":
49 console.error("Error:", result.error_message);
50 break;
51 }
52 });
53}

TypeScript Types

The ipflare library provides comprehensive TypeScript types for all operations:

1import {
2 IPFlare,
3 type BulkLookupOptions,
4 type BulkLookupResponse,
5 type IPGeolocationError,
6 type IPGeolocationOptions,
7 type IPGeolocationResponse,
8 type IPGeolocationSuccess,
9 type LookupOptions,
10 type Result,
11 type ErrorType,
12 // Type guard functions
13 isSuccess,
14 isError,
15 isIPGeolocationError,
16 isIPGeolocationSuccess,
17} from "ipflare";

Advanced Features

Input Validation

The library performs comprehensive client-side validation to prevent invalid requests and provide immediate feedback:

1// These will return error results immediately (no API call made)
2const invalidIPResult = await geolocator.lookup("invalid-ip");
3if (!invalidIPResult.ok) {
4 console.error(invalidIPResult.error.message); // "Invalid IP address format: invalid-ip"
5}
6
7const emptyBulkResult = await geolocator.bulkLookup({ ips: [] });
8if (!emptyBulkResult.ok) {
9 console.error(emptyBulkResult.error.message); // "At least one IP address is required"
10}
11
12const tooManyIPsResult = await geolocator.bulkLookup({
13 ips: new Array(501).fill("1.1.1.1")
14});
15if (!tooManyIPsResult.ok) {
16 console.error(tooManyIPsResult.error.message); // "Maximum of 500 IPs per request allowed"
17}

Error Reference

Error Types

The library provides structured error types that match the actual API responses:

  • INVALID_IP_ADDRESS - Invalid IP address format
  • RESERVED_IP_ADDRESS - IP address is reserved (private/local)
  • GEOLOCATION_NOT_FOUND - Geolocation data not available for this IP
  • INTERNAL_SERVER_ERROR - Server-side error occurred
  • INVALID_INPUT - Invalid input parameters
  • UNAUTHORIZED - Invalid or missing API key
  • QUOTA_EXCEEDED - API quota exceeded
  • NO_API_KEY_PROVIDED - No API key was provided
  • NETWORK_ERROR - Network connectivity issues
  • VALIDATION_ERROR - Client-side input validation errors
  • UNKNOWN_ERROR - Unexpected errors

Result Type Structure

All methods return a Result type with the following structure:

1// Success result
2type SuccessResult<T> = {
3 ok: true;
4 data: T;
5}
6
7// Error result
8type ErrorResult = {
9 ok: false;
10 error: {
11 type: ErrorType;
12 message: string;
13 details?: unknown;
14 };
15}
16
17// Combined result type
18type Result<T> = SuccessResult<T> | ErrorResult;

Common Error Messages

The library provides specific error messages for different scenarios:

  • "API key is required" - No API key provided
  • "API key must be a string" - Invalid API key type
  • "API key cannot be empty" - Empty API key
  • "IP address is required" - No IP address provided
  • "IP address must be a string" - Invalid IP type
  • "Invalid IP address format: [ip]" - Invalid IP format
  • "IPs must be an array" - Invalid bulk IPs type
  • "At least one IP address is required" - Empty IP array
  • "Maximum of 500 IPs per request allowed" - Too many IPs
  • "Invalid IP addresses found: [ips]" - Invalid IPs in bulk request request
  • "Invalid API key" - HTTP 401 response
  • "Quota exceeded" - HTTP 429 response (usage quota exceeded)