Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the IP of a user in Nuxt's asyncData method?

Nuxt uses asyncData to run code server-side and then merges it with the data object.

I want to make a call that requires me to know the user's IP. I see that I can get to the req object which does have it but it's buried deep, deep in there and I worry this is not a reliable way of doing it.

How can I access the calling user's IP address server-side instead of client-side?

like image 474
dsp_099 Avatar asked Oct 16 '25 19:10

dsp_099


2 Answers

If nuxt is running behind a proxy such as nginx, then you can get the client's IP address in asyncData by reading x-real-ip or x-forwarded-for. Be aware that x-forwarded-for can contain comma separated IPs if a call has passed through additional proxys (if there is multiple entries, then the client is the first one).

Make sure to set up the headers in your nginx site configuration

proxy_set_header Host $host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

Then you can read the headers in asyncData:

  async asyncData(context) {
    if (process.server) {
      const req = context.req
      const headers = (req && req.headers) ? Object.assign({}, req.headers) : {}
      const xForwardedFor = headers['x-forwarded-for']      
      const xRealIp = headers['x-real-ip']
      console.log(xForwardedFor)
      console.log(xRealIp)
    }
  }
like image 97
Chris Nilsson Avatar answered Oct 19 '25 08:10

Chris Nilsson


There was a github thread about this which makes grabbing the IP trivial in both environments (locally, production)

const ip = req.connection.remoteAddress || req.socket.remoteAddress

But be aware that you'll need to ensure the proxy headers are forwarded correctly. Because nuxt runs behind a traditional web server, without having the proxy headers forwarded, you'll always get the Local IP of the web server (127.0.0.1 unless loop back was changed).

like image 35
Ohgodwhy Avatar answered Oct 19 '25 08:10

Ohgodwhy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!