Search code examples
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

  • A shorter method that doesn't require using any third-party libraries or services.

    import { NextRequest, NextResponse } from "next/server";
    import { headers } from "next/headers";
    
    /** @param {NextRequest} req */
    export async function GET(req) {
      const { ua } = userAgent(req);
    
      const headersList = headers();
      const ip = headersList.get("x-forwarded-for");
    
      const data = {
        ok: true,
        ip_address: ip,
        user_agent: ua,
      };
    
      return NextResponse.json(data, { status: 200 });
    }
    

    Now, this code example answers your question.