UNPKG

@designerstrust/remix-utils

Version:

This package contains simple utility functions to use with [Remix.run](https://remix.run).

50 lines (49 loc) 1.43 kB
import isIP from "is-ip"; import { getHeaders } from "./get-headers"; /** * This is the list of headers, in order of preference, that will be used to * determine the client's IP address. */ const headerNames = Object.freeze([ "X-Client-IP", "X-Forwarded-For", "Fly-Client-IP", "CF-Connecting-IP", "Fastly-Client-Ip", "True-Client-Ip", "X-Real-IP", "X-Cluster-Client-IP", "X-Forwarded", "Forwarded-For", "Forwarded", "DO-Connecting-IP" /** Digital ocean app platform */, ]); export function getClientIPAddress(requestOrHeaders) { let headers = getHeaders(requestOrHeaders); let ipAddress = headerNames .flatMap((headerName) => { let value = headers.get(headerName); if (headerName === "Forwarded") { return parseForwardedHeader(value); } if (!(value === null || value === void 0 ? void 0 : value.includes(","))) return value; return value.split(",").map((ip) => ip.trim()); }) .find((ip) => { if (ip === null) return false; return isIP(ip); }); return ipAddress !== null && ipAddress !== void 0 ? ipAddress : null; } function parseForwardedHeader(value) { if (!value) return null; for (let part of value.split(";")) { if (part.startsWith("for=")) return part.slice(4); continue; } return null; }