Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

getIPAddress

Fetches the public IP address of the client using the ipify API (https://api.ipify.org: free, no API key required). Handles HTTP errors (!res.ok) and network or JSON parse failures gracefully.

TypeScript
Copied!
1/**
2 * Fetches the public IP address of the client using the ipify API.
3 *
4 * @returns The IP address as a string, or 'null' in case of failure.
5 */
6export async function getIPAddress(): Promise<string | null> {
7  try {
8    const res = await fetch('https://api.ipify.org?format=json');
9    if (!res.ok) return null;
10    const data = await res.json();
11    return typeof data.ip === 'string' ? data.ip : null;
12  } catch {
13    return null;
14  }
15}
  • Simple External IP Retrieval

    Abstracts away the complexities of networking by using a well-known third-party API (ipify) to get the public-facing IP.

  • Fail-Safe Behavior

    Returns null on failure instead of throwing, making it safe to use in environments where connectivity might be unstable.

  • Type-Safe and Explicit Return

    Validates that the returned ip is a string, adding robustness against unexpected API changes or malformed responses.

  • Minimal Overhead

    Uses only a single lightweight GET request with a concise JSON response, keeping bandwidth usage low.

Tests | Examples

TypeScript
Copied!
1global.fetch = jest.fn();
2
3afterEach(() => {
4  jest.clearAllMocks();
5});
6
7test('returns IP address when API responds correctly', async () => {
8  (fetch as jest.Mock).mockResolvedValue({
9    ok: true,
10    json: async () => ({ ip: '123.45.67.89' }),
11  });
12
13  const ip = await getIPAddress();
14  expect(ip).toBe('123.45.67.89');
15  expect(fetch).toHaveBeenCalledWith('https://api.ipify.org?format=json');
16});
17
18test('returns null when response is not ok', async () => {
19  (fetch as jest.Mock).mockResolvedValue({ ok: false });
20  const ip = await getIPAddress();
21  expect(ip).toBeNull();
22});
23
24test('returns null on network or parsing error', async () => {
25  (fetch as jest.Mock).mockRejectedValue(new Error('Network error'));
26  const ip = await getIPAddress();
27  expect(ip).toBeNull();
28});

Common Use Cases

  • Audit Logging or Analytics

    Capture the client’s public IP for logging or user behavior tracking in analytics tools.

  • Geo-Location Services

    Use the IP address to infer geographic location or language preferences via additional services.

  • Security Checks or Rate Limiting

    Identify clients for IP-based access control, fraud detection, or throttling.

  • Debugging and Diagnostics

    Show end users or developers their current public IP for connectivity troubleshooting.

Codebase: Utilities -> Network -> getIPAddress | Yevhen Klymentiev