How to get user IP address in Vue.js

Viewed 10396

I'm new in Vue.js. I need to get user ip address inside Vue.js.

What i have to do before is req.ip inside API, but my API always get Vue.js server IP.

So i think Vue.js that must determine what user ip is. But i still not find a best way to get user ip inside Vue.js. Anyone help ?

2 Answers

You need to send a request to expose the clients IP to some API. For instance you can do the following request with only vanilla JS (in mounted() for example) and then save the IP to data.

fetch('https://api.ipify.org?format=json')
  .then(response => response.json())
  .then(response => {
    this.clientIp = response.ip;
  });

I'm making a few assumptions here, but if you're using nodejs and express for your server behind a proxy, you can add this to have req.ip give you the client IP:

var app = express();
app.set('trust proxy', true);

Then your API idea would work.

Related