2

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.

EverStarck
  • 33
  • 1
  • 1
  • 6

3 Answers3

7

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 },
  };
};
Diogo Capela
  • 5,669
  • 5
  • 24
  • 35
2

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,
    },
  }
}
Merlo
  • 631
  • 1
  • 6
  • 11
0

I think you can get them through getServerSideProps.

export async function getServerSideProps({ req }) {
  console.log(req.headers) //see if you have those headers
  return {
    props: {
      headers
    },
  }
}

function Page({ headers }) {
  // Render data...
}
Ryan Wu
  • 5,963
  • 2
  • 36
  • 47
  • I tried it and it didn't work, so I used the API Routes and it works, but only got the data from `http://localhost:3000/api`. Fortunately I found a solution to the problem, which is basically here: [github link](https://github.com/vercel/next.js/issues/9524#issuecomment-589772756) . The only problem is now that I don't know how to get the IP, because `getData()` which is what is called in the page, does not have req as a parameter, so the header that I occupy is returned undefined. – EverStarck Feb 10 '21 at 04:09