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.

Noah
  • 4,601
  • 9
  • 39
  • 52

1 Answers1

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.

Sven
  • 5,155
  • 29
  • 53
  • I have tried `this.request.ip`, but it shows the IP of my front-end site, not my actual IP address. – Noah Jan 01 '16 at 17:52
  • 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) – Sven Jan 01 '16 at 17:55
  • 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. – Noah Jan 01 '16 at 18:15
  • 1
    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. https://github.com/koajs/koa/blob/master/docs/api/index.md#settings – danneu Jan 07 '16 at 19:12