NextJS How to get client IP from the request with code examples

This tutorial explains how to get Client IP address from a request in NextJS. One way is to get the IP address in Front end components, and Another way using backend API routes. Third way using the request-ip npm library

NextJS how to get the Client IP Address from a Request with API Routes

NextJS provides NextRequest which is similar to the http native request. NextRequest.ip address gives route address.

import { NextRequest } from 'next/server'
import type { NextApiRequest, NextApiResponse } from "next";
import { NextRequest } from "next/server";

export default function handler(req: NextRequest, res: NextRequest) {
  const detectedIp = req.ip;
  console.log(detectedIp);
}

NextJS on Client Side routes to get IP Address

In this example, Get IP Address on Client side.

  • In React component, write the getInitialProps method that contains
  • call req.headers[“x-real-ip”] , if this value is undefined, get the value from req.connection.remoteAddress
  • Return the object that contains ip value
  • Pass this object to react component to display in UI

Here is an example

export default function Home({ ip }) {
  return (
    <div>
      <h1>IP Remote address: {ip}</h1>
    </div>
  );
}
Home.getInitialProps = async ({ req }) => {
  const ip = req.headers["x-real-ip"] || req.connection.remoteAddress;
  return { ip };
};

NextJS request-ip npm library to Get Remote IP address

request-ip🔗 is a third-party small node library that provides us get IP address as a string.

You can install this library to get IP Address in API routes in the NextJS Application.

Install npm using the below command in the terminal

npm install request-ip

requestIp class import into API route.

import requestIp from "request-ip";

Next, call requestIp.getClientIp(req) to get the Client IP Address.

Here is an example

// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type { NextApiRequest, NextApiResponse } from "next";
import requestIp from "request-ip";

type Data = {
  name: string,
};

export default function handler(
  req: NextApiRequest,
  res: NextApiResponse<Data>
) {
  let ip;

  const detectedIp = requestIp.getClientIp(req);
  console.log(detectedIp);
  res.status(200).json({ name: "John Doe" });
}

How do I find the client IP address in NextJS?

To get the Client Ip address in NextJS, Please follow the below steps

  • NextJS provides NextRequest in Server Code, It is a wrapper of Native Request Object.
  • Import, NextRequest in API routes in the server side
import type { NextRequest } from 'next/server'
  • call NextRequest.ip property to get the IP Address of a Server request.