With separate client and server apps, how do I get a user's IP address, in Node with Koa?
Asked Answered
G

1

0

I have two apps, one front end and one a REST API back-end. How do I get the IP address of the user accessing the back-end when the front-end client makes a request to the back-end?

I have tried this.request.ip, but it shows the IP of my front-end site, not my actual IP address.

Globate answered 1/1, 2016 at 7:22 Comment(0)
K
0

That would be in the HTTP incoming request object. I don't know what property in the object from the top of my head, but you'll find it in your route if you simply log the request: console.log(this.request). You can bypass Koa and get the raw Node request object with this.req instead - but I'm sure the client IP is available in the Koa request as well.

Krisha answered 1/1, 2016 at 8:7 Comment(4)
I have tried this.request.ip, but it shows the IP of my front-end site, not my actual IP address.Globate
What do you mean "front-end site"? If it's similar to 127.0.0.1 or 0.0.0.0 it's because you're testing locally on your computer. If you're testing this in production, it could be that you're behind a proxy. In that case, see if the x-forwarded-for header is present. Try these: this.req.connection.remoteAddress or this.req.headers["x-forwarded-for"] (note that these uses the raw Node request object, should be similar functionality in Koa)Krisha
There is one server hosting the front-end site. It hosts a javascript front-end. Then an API server, the back-end. The address is not my IP address or any local address. I believe it is a heroku address.Globate
If you set app.proxy = true, then this.request.ip will use X-Forwarded-For if it exists. This is nicer because if you ever happen to drop the proxy, you can simply set it back to false (the default). It also lets this.request.ip work in environments where you aren't using a proxy, like on a staging server, in development, etc. github.com/koajs/koa/blob/master/docs/api/index.md#settingsOrsola

© 2022 - 2024 — McMap. All rights reserved.