Next.js Discord

Discord Forum

How to get the IP from a NextRequest

Unanswered
Artois Hound posted this in #help-forum
Open in Discord
Artois HoundOP
I am currently attempting to get the IP this way:
// Get client IP
  const ip =
    request.headers.get("x-real-ip") ||
    request.headers.get("x-forwarded-for") ||
    request.ip ||
    "unknown";
  console.log(ip);


And I get "unknown" each time 🤔 Any idea how to do it properly?

10 Replies

Artois HoundOP
I am basically using almost the same thing as this tutorial but it does not work: https://reacthustle.com/blog/nextjs-get-user-ip
Artois HoundOP
Ok so with port forwarding I got 10.240.3.108
Still not the actual IP, but some special IP but meh
Artois HoundOP
I will assume that it just doesn't work in local environments, but if anyone has some comments, lemme know.
this is really frequently asked question. in fact it is a bit complex to get IP address.
i would recommend you to use Cloudflare worker, which Vercel uses under the hood.
here is my poc project to get IP in middleware.ts
in case of local network, running ngrok as proxy might work.
Artois HoundOP
I mean, my code might actually work since upon testing it further, I can get Private IPs such as: 10.240.4.232

The reason I don't get actual IP is probably because I'm using port-forwarding.
Yep, I tried different IPs and I got different Private IPs too: IP: 10.240.0.10
IP: 10.240.0.222
So I think the code works, I will just have to deploy on a VPS for it to get the actual IPs.