@catho/request-public-ip
Version:
Node.js module for retrieving a request's public IP address
35 lines (32 loc) • 1.1 kB
JavaScript
import { isPublicIp } from './is-public-ip.mjs';
function getClientPublicIpFromHeaders(headers) {
// Used by Amazon EC2, Heroku, and others.
if (isPublicIp(headers["x-client-ip"])) {
return headers["x-client-ip"];
}
// Used by Load-balancers (AWS ELB) or proxies.
const xForwardedFor = getClientPublicIpFromXForwardedFor(headers["x-forwarded-for"]);
if (xForwardedFor) {
return xForwardedFor;
}
// Used by Akamai and Cloudflare
if (isPublicIp(headers["true-client-ip"])) {
return headers["true-client-ip"];
}
// Used by nginx proxy/fcgi; alternative to x-forwarded-for
if (isPublicIp(headers["x-real-ip"])) {
return headers["x-real-ip"];
}
}
function getClientPublicIpFromXForwardedFor(input) {
if (!input)
return;
const ips = Array.isArray(input) ? input : input.split(",");
for (let i = 0; i < ips.length; i++) {
const ip = ips[i].trim();
if (isPublicIp(ip)) {
return ip;
}
}
}
export { getClientPublicIpFromHeaders, getClientPublicIpFromXForwardedFor };