Search code examples
nuxt.jsip-address

How can I get client IP address in Nuxt.js?


I want to know how to get client IP address in Nuxt.js. I am using Nuxt.js in client side and Express in server side. I thought I can get a client ip address in the server side by req.connection.remoteAddress or req.headers['x-forwarded-for'].split(',').pop() when server side receives an request. However, by above codes, I can only get ::ffff:127.0.0.1.

I google and found that if I am using nginx, I can set x-forwarded-for by setting file, but I am not using nginx. I may be using @nuxtjs/proxy (but I am not sure. I'm sorry but I do not understand proxy well.)

modules: [
 '@nuxtjs/axios',
 '@nuxtjs/pwa',
 '@nuxtjs/proxy',
 '@nuxtjs/auth',
],
proxy: {
 '/api/': {
   target: process.browser ? '' : 'http://localhost:3001',
   pathRewrite: { '^/api/': '/' },
 },
}

(A part of nuxt.config.js.)

By reading document of @nuxtjs/proxy it seems that I can set 'x-forwarded-for' header, but I do not know how to get client ip address its self, and I cannot set the header.

As an another way, I tried to set client ip address as a parameter, and used following codes.

client side

if (process.browser) {
  const ip = await this.$axios.$get('/ip/')
}
// send an request with this ip as a parameter.

nuxt.config.js

proxy: {
    '/api/': {
      target: process.browser ? '' : 'http://localhost:3001',
      pathRewrite: { '^/api/': '/' },
    },
    '/ip/': {
      target: process.browser ? 'http://icanhazip.com' : 'http://icanhazip.com',
      pathRewrite: { '^/ip/': '/' },
    },
  },

But I can only get the same, server side, global ip address although I used process.browser.

Please help me to get client ip address in Nuxt.js. Thank you.


Solution

  • For Nuxt checkout the code described in this discusion - https://github.com/nuxt/nuxt.js/issues/2914

    Basically thel idea is to store the client IP in the request that the proxy recieves

    export default ({ req, store }) => {
      if (process.server) {
        // https://github.com/nuxt/nuxt.js/issues/2914
        const ip = req.connection.remoteAddress || req.socket.remoteAddress
        store.commit('SET_IP', ip)
      }
      if (process.client) {
        localStorage.setItem('ip', store.getters.ip)
      }
    }