๐Ÿ“ฆ ronitrajfr / ayoni

๐Ÿ“„ getIP.ts ยท 23 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23import { isIP } from "net";

export function getIp(headers: Headers): string {
  const forwardedFor = headers.get("x-forwarded-for");
  const realIp = headers.get("x-real-ip");

  if (forwardedFor) {
    const firstIp = forwardedFor.split(",")[0]?.trim();
    if (firstIp && isIP(firstIp)) {
      return firstIp;
    }
  }

  if (realIp) {
    const trimmedIp = realIp.trim();
    if (isIP(trimmedIp)) {
      return trimmedIp;
    }
  }

  return "127.0.0.1";
}