@geoipapi/sdk
v0.0.1
Published
<div align="center">
Readme
🌍 GeoIP API TypeScript SDK
Developer-friendly & type-safe TypeScript SDK for enterprise IP geolocation
Features • Installation • Quick Start • API Reference • Examples
📋 Table of Contents
- 🎯 Overview
- ✨ Features
- 🚀 Installation
- ⚡ Quick Start
- 📖 API Reference
- 💡 Examples
- 🏗️ Project Structure
- ⚙️ Configuration
- 🧪 Testing
- 🤝 Contributing
- 📝 License
🎯 Overview
The GeoIP API TypeScript SDK is a high-performance, enterprise-grade client library that provides real-time IP geolocation data for personalization, analytics, and security applications. Built with TypeScript-first design principles, it offers complete type safety and an intuitive developer experience.
What makes this SDK special?
- 🔒 Type-Safe: Full TypeScript support with comprehensive type definitions
- ⚡ High Performance: Optimized for speed with minimal bundle size
- 🌐 Multiple Formats: Support for JSON, JSONP, XML, and YAML responses
- 🔄 Auto-Retry: Built-in retry logic with configurable backoff strategies
- 📦 Tree-Shakable: Import only what you need for optimal bundle size
- 🎯 MCP Support: Compatible with Model Context Protocol for AI applications
✨ Features
| Feature | Description | |---------|-------------| | IP Detection | Automatically detect visitor's IP address | | Geolocation Data | Get detailed location information including country, city, timezone | | ISP Information | Access ASN, network provider, and connection type data | | Currency & Language | Retrieve local currency codes and language preferences | | Security Insights | Identify proxy, VPN, and hosting provider connections | | Flexible Formats | Support for JSON, XML, YAML, and JSONP responses | | Rate Limiting | Built-in respect for API rate limits | | Error Handling | Comprehensive error types with detailed information |
🚀 Installation
Choose your preferred package manager:
# NPM
npm install @geoipapi/sdk
# PNPM
pnpm add @geoipapi/sdk
# Bun
bun add @geoipapi/sdk
# Yarn
yarn add @geoipapi/sdk zodNote: Yarn requires manual installation of the
zodpeer dependency.
⚡ Quick Start
import { GeoIp } from "geoipapi";
// Initialize the client
const geoIp = new GeoIp();
// Get your current IP address
async function getCurrentIP() {
try {
const ip = await geoIp.geoIPEndpoints.getIp();
console.log("Your IP:", ip);
} catch (error) {
console.error("Failed to get IP:", error);
}
}
// Get detailed geolocation data
async function getLocationData() {
try {
const result = await geoIp.geoIPEndpoints.getIpData();
console.log("Location data:", result);
/*
Expected output:
{"ip":"103.105.180.16","type":"IPv4","country":{"is_eu_member":false,"currency_code":"CNY","continent":"AS","name":"China","country_code":"CN","state":"Wuhan Shi","city":"Hankou (Wuchang Qu)","zip":null,"timezone":"Asia/Shanghai"},"location":{"latitude":30.552964677185926,"longitude":114.34486005697988},"asn":{"number":63539,"name":"Cloud Union (HuBei) Network Technology Co., Ltd","network":"103.105.180.0/22","type":"HOSTING"}}
*/
} catch (error) {
console.error("Failed to get location data:", error);
}
}
// Run the examples
getCurrentIP();
getLocationData();📖 API Reference
Core Methods
getIp()
Get the current IP address of the requester.
const ip: string = await geoIp.geoIPEndpoints.getIp();getIpData(request?)
Get comprehensive geolocation data for your IP address.
const data = await geoIp.geoIPEndpoints.getIpData();Response Schema
interface GeoLocationResponse {
ip: string;
type: "IPv4" | "IPv6";
country: {
name: string;
country_code: string;
currency_code: string;
is_eu_member: boolean;
continent: string;
state?: string;
city?: string;
zip?: string;
timezone: string;
};
location: {
latitude: number;
longitude: number;
};
asn: {
number: number;
name: string;
network: string;
type: string;
};
}💡 Examples
Basic Usage
import { GeoIp } from "geoipapi";
const client = new GeoIp();
// Simple IP lookup
const userIP = await client.geoIPEndpoints.getIp();
const locationData = await client.geoIPEndpoints.getIpData();Error Handling
import { GeoIp } from "geoipapi";
import * as errors from "geoipapi/models/errors";
const client = new GeoIp();
try {
const result = await client.geoIPEndpoints.getIpData({ ip: "invalid-ip" });
} catch (error) {
if (error instanceof errors.HTTPValidationError) {
console.log("Validation error:", error.data$.detail);
} else if (error instanceof errors.GeoIPError) {
console.log("API error:", error.message, error.statusCode);
} else {
console.log("Unexpected error:", error);
}
}Standalone Functions (Tree-Shaking Friendly)
import { GeoIpCore } from "geoipapi/core.js";
import { geoIPEndpointsGetIP, geoIPEndpointsGetIPData } from "geoipapi/funcs";
const client = new GeoIpCore();
// Tree-shakable function calls
const ipResult = await geoIPEndpointsGetIP(client);
const dataResult = await geoIPEndpointsGetIPData(client, { ip: "1.1.1.1" });
if (ipResult.ok) {
console.log("IP:", ipResult.value);
}
if (dataResult.ok) {
console.log("Data:", dataResult.value);
}Custom HTTP Client
import { GeoIp, HTTPClient } from "geoipapi";
const httpClient = new HTTPClient({
fetcher: (request) => fetch(request)
});
// Add custom headers
httpClient.addHook("beforeRequest", (request) => {
const nextRequest = new Request(request, {
signal: request.signal || AbortSignal.timeout(10000)
});
nextRequest.headers.set("User-Agent", "MyApp/1.0");
return nextRequest;
});
// Custom error logging
httpClient.addHook("requestError", (error, request) => {
console.error(`Request failed: ${request.method} ${request.url}`, error);
});
const client = new GeoIp({ httpClient });🏗️ Project Structure
geo-ip-typescript/
├── 📁 src/ # Source code
│ ├── 📁 models/ # TypeScript type definitions
│ ├── 📁 lib/ # Core SDK functionality
│ └── 📁 funcs/ # Standalone functions
├── 📁 docs/ # API documentation
│ └── 📁 sdks/ # SDK-specific docs
├── 📁 dist/ # Compiled JavaScript
├── 📄 README.md # This file
├── 📄 USAGE.md # Usage examples
├── 📄 CONTRIBUTING.md # Contribution guidelines
├── 📄 package.json # Package configuration
└── 📄 tsconfig.json # TypeScript configuration⚙️ Configuration
Environment Variables
# Enable debug logging
GEOIP_DEBUG=true
# Custom API endpoint (optional)
GEOIP_API_URL=https://api.geoipapi.comClient Configuration
const client = new GeoIp({
serverURL: "https://api.geoipapi.com", // Custom API URL
retryConfig: { // Retry configuration
strategy: "backoff",
backoff: {
initialInterval: 1000,
maxInterval: 30000,
exponent: 1.5,
},
},
debugLogger: console, // Debug logging
});🧪 Testing
This SDK includes comprehensive test coverage. For supported JavaScript runtimes, please consult RUNTIMES.md.
# Run tests
npm test
# Run with coverage
npm run test:coverage
# Run linting
npm run lint
# Type checking
npm run type-check🤝 Contributing
We welcome contributions! However, please note that this repository contains generated code.
How to Contribute
- Report Issues: Open a GitHub issue with detailed information about bugs or feature requests
- Provide Feedback: Share your experience and suggestions for improvements
- Documentation: Help improve examples and documentation
Issue Guidelines
When reporting issues, please include:
- Clear and descriptive title
- Steps to reproduce the issue
- Expected vs actual behavior
- Environment information (
npx envinfo) - Relevant logs or error messages
For more details, see CONTRIBUTING.md.
📝 License
This project is licensed under the MIT License.
Made with ❤️ for developers who need reliable IP geolocation data
