Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
51
rated 0 times [  52] [ 1]  / answers: 1 / hits: 10862  / 5 Years ago, sat, august 3, 2019, 12:00:00

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?


More From » vue.js

 Answers
0

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)
}
}

[#6700] Thursday, August 1, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mira

Total Points: 460
Total Questions: 108
Total Answers: 99

Location: American Samoa
Member since Fri, Aug 26, 2022
2 Years ago
mira questions
;