Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the client IP on NextJS and use SSR

I'm making a weather app, and I get the client IP with IPIFY, but this loses SSR, or I use SSR and I get the server IP. Someone told me that I could use the header x-forwarded-for and then, with this value, make the weather API call with SSR.

The problem is I'm using only nextjs, no backend here, and second, I don't know how to call or use x-forwarded-for in the front to get the client IP.

  1. Is this possible?

  2. How I can implement that?

I'm using vercel to deploy the app.

like image 211
EverStarck Avatar asked Sep 05 '25 03:09

EverStarck


2 Answers

Updated answer as request.connection is deprecated since Node.js v13.0.0. So we should now use request.socket instead.

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 },
  };
};
like image 110
Diogo Capela Avatar answered Sep 08 '25 00:09

Diogo Capela


Here you go:

export async function getServerSideProps({ req }) {
  const forwarded = req.headers["x-forwarded-for"]
  const ip = forwarded ? forwarded.split(/, /)[0] : req.connection.remoteAddress
  return {
    props: {
      ip,
    },
  }
}
like image 36
Merlo Avatar answered Sep 07 '25 23:09

Merlo