1

I am trying to find the IP of the client in getServerSideProps in NextJs. I simply use basic IP found methods but when I call that method in getServerSideProps which always giving me the server IP, not Client IP.

Archana Agivale
  • 317
  • 1
  • 3
  • 14

1 Answers1

3

You can do it like this:

export const getServerSideProps = async ({ req }) => {
  const forwarded = req.headers['x-forwarded-for'];

  const ip = typeof forwarded === 'string' ? forwarded.split(/, /)[0] : req.socket.remoteAddress;

  console.log(ip);

  return {
    props: { ip },
  };
};
Diogo Capela
  • 5,669
  • 5
  • 24
  • 35
  • Curiously this only seems to get the private IP address, even when NextJS is deployed to a non-localhost environment. Curious if anyone else has encountered this and found a solution. – dylangrandmont Mar 01 '23 at 21:20