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?
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?
Share Improve this question asked Aug 3, 2019 at 3:16 dsp_099dsp_099 6,12120 gold badges78 silver badges131 bronze badges2 Answers
Reset to default 10If 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 ma 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)
}
}
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).