Get client IP in Koa.js
Asked Answered
T

3

14

I have a Koa app with a handler like this:

router.get('/admin.html', function *(next) {
    const clientIP = "?";
    this.body = `Hello World ${clientIp}`;
});

where I need to acquire the client's IP address to form the response. How can I assign clientIp so it refers to the IP address the request originates from.

Tergal answered 7/6, 2016 at 20:27 Comment(0)
T
19

Koa 1:

Assuming you have no reverse proxy in place, you can use this.request.ip like this:

router.get('/admin.html', function *(next) {
    const clientIP = this.request.ip;
    this.body = `Hello World ${clientIP}`;
});

This feature is documented in the request documentation. You can always access said request object as this.request.

If you have a reverse proxy in place, you'll always get the IP address of the reverse proxy. In this case, it's more tricky: In the reverse proxy configuration, you need to add a special header, e.g. X-Orig-IP with the original client IP.

Then, you can access it in koa with:

const clientIp = this.request.headers["X-Orig-IP"];

Koa 2:

The approach is quite similar, only the syntax is slightly different:

router.get('/', async (ctx, next) => {
    const clientIP = ctx.request.ip;
    ctx.body = `Hello World ${clientIP}`;
})
Tergal answered 7/6, 2016 at 20:27 Comment(3)
@Qasim I'll add an example.Rimrock
I'm getting an ipv6 ip back, is it possible to get ipv4?Ivelisseivens
@Ivelisseivens In that case your client connects to the server using IPv6. Disable IPv6 on the server to avoid that.Rimrock
C
5

If you add app.proxy=true you can still use request.ip without having to worry about the IP headers.

Colchicum answered 1/8, 2017 at 6:43 Comment(0)
M
5

I had the same problem but resolved it by using this module found on NPM request-ip

in koa it can be simply used userIp = requestIp.getClientIp(ctx.request)

The user ip is determined by the following order:

X-Client-IP
X-Forwarded-For (Header may return multiple IP addresses in the format: "client IP, proxy 1 IP, proxy 2 IP", so we take the the first one.)
CF-Connecting-IP (Cloudflare)
Fastly-Client-Ip (Fastly CDN and Firebase hosting header when forwared to a cloud function)
True-Client-Ip (Akamai and Cloudflare)
X-Real-IP (Nginx proxy/FastCGI)
X-Cluster-Client-IP (Rackspace LB, Riverbed Stingray)
X-Forwarded, Forwarded-For and Forwarded (Variations of #2)
req.connection.remoteAddress
req.socket.remoteAddress
req.connection.socket.remoteAddress
req.info.remoteAddress

If an IP address cannot be found, it will return null.

Metanephros answered 24/7, 2021 at 20:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.