0

I have to send a user IP into the logging service on page load. I use static mode in my next.js app.

I have an idea to use an edge function to get visitor IP, pass it as header and then read this value on the frontend. How can I read it? Is there any other reasonable option to pass information like IP or geo into the frontend?

Thanks!

Dominik
  • 91
  • 5
  • I would utilize an api service to do this, most provide 10k+ free per month and then you can cale up as needed - https://stackoverflow.com/questions/391979/how-to-get-clients-ip-address-using-javascript – Ramakay Mar 01 '22 at 15:56

1 Answers1

0

As I know you can get IP by using getServerSideProps but this approach change page from static to server render more info. You use it inside the page file like this:

export async function getServerSideProps(context) {
  return {
    props: {}, // will be passed to the page component as props
  }
}

context in this case contains user ip you can get it like this:

const ip = context.req.headers["x-forwarded-for"] || context.req.socket.remoteAddress;

and than you can pass it to the frontend or send another request with this ip:

 export async function getServerSideProps(context) {
      const ip = context.req.headers["x-forwarded-for"] || context.req.socket.remoteAddress;
      return {
        props: { ip }, // will be passed to the page component as props
      }
    }

and then catch it and use it in your component:

export default function MyPage({ ip }) {...}

Sending ip from getServerSideProps to the server

you can get ip also on you backend if you using Node.js and express inside req:

const myFn = (req, res, next) => {
    const ip = req.headers["x-forwarded-for"] || req.socket.remoteAddress;
}

but if you send request from getServerSideProps there will be your Next.js server ip not user ip. So you need manually add header with ip when you sending request from the getServerSideProps for example with axios (it is better to use interceptors for convenience):

axios.post("/some/route", {...},{
    headers: { "client-ip": ctx.req.headers["x-forwarded-for"] || ctx.req.socket.remoteAddress },
  });

and than on the Node.js backend:

const myFn = (req, res, next) => {
    const ip = req.headers["client-ip"] || req.headers["x-forwarded-for"] || req.socket.remoteAddress;
}

and with all this you can get your user ip in all scenarios.

Note

When you working with localhost you will get ::1 as ip but in production it works as expected.