next.jsip-addressnext.js13

How to get client's ip address in Next.js 13?


I have a next.js 13 app and want to add an API endpoint /api/getIP.

The route.js file is in the /app/api/getIP/route.js.

Minimal Reproduceable Code: https://github.com/Nusab19/nextjs-test/tree/main/app

I tried several ways of doing it but none of them worked. I tried using request-ip to get the ip but it returned null.

Here is my code:

import { NextResponse } from "next/server";
import requestIp from "request-ip";

export async function GET(req) {
  const detectedIp = requestIp.getClientIp(req);
  const data = {
    ok: true,
    ip: detectedIp,
    userAgent: req.headers.get("user-agent"),
  };
  return new NextResponse(JSON.stringify(data, null, 2));
}

I get this response when I visit:

{
    "ok": true,
    "ip": null,
    "userAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36"
}

Solution

  • There is a new way to do it in Nextjs 15 using ipAddress as NextRequest no longers holds an ip property.

    req.ip --> ipAddress(req)

    console.log(ipAddress(req)) might show undefined on local environment, but don't worry, deploy it on Vercel for it to work (check server logs).