Insightcn

getClientIp

Extract client IP from request headers.

Extract client IP from request headers (x-forwarded-for, x-real-ip).

Signature

function getClientIp(request: Request): string | null;

Parameters

ParameterTypeDescription
requestRequestThe incoming request

Returns

string | null — The client IP address, or null if not found.

Example

import { getClientIp } from "@insightcn/sdk";

const ip = getClientIp(request);
console.log(ip); // "192.168.1.100"

Header Priority

The function checks headers in the following order:

  1. x-forwarded-for — Common proxy header (may contain multiple IPs)
  2. x-real-ip — Nginx proxy header

x-forwarded-for Format

The x-forwarded-for header may contain multiple IPs:

x-forwarded-for: 192.168.1.100, 10.0.0.1, 172.16.0.1

The function extracts the first IP (the original client IP).

Use Cases

  • Logging — Record client IP for debugging
  • Analytics — Track geographic distribution
  • Security — Identify suspicious activity

Privacy Considerations

Remember to anonymize IPs before storing them:

import { anonymizeIp, getClientIp } from "@insightcn/sdk";

const ip = getClientIp(request);
if (ip) {
  const anonymized = anonymizeIp(ip);
  // Store anonymized IP
}

On this page