简体   繁体   中英

How can I get user's IP address using NginX + Next.JS + Apollo GraphQL

I'm using next.js app, graphql server, and nginx.

I have to grep client ip address.

So in my nginx conf file, I added

 ...

 location / {
    proxy_pass http://localhost:3000;     # next.js server (3000)
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
    proxy_cache_bypass $http_upgrade;
}

location /graphql {
    proxy_set_header X-Real-IP $remote_addr;
    proxy_pass http://localhost:4000/graphql;        # graphql server (4000)
}

And In my graphql, I added

const ip = context.req.header('X-Real-IP')
console.log(ip)

Now I can get client IP very well !

But, the problem is when user doing SSR (refresh page)

The ip address is 127.0.0.1 or localhost

How could I get real ip address even if user is in server side rendering?

Looks like your Next.js makes a server to server call, therefore you get the localhost ip.

You need to attach the user ip that you get in Next.js to the request it makes to the GQL server.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM