Search code examples
javascriptnode.jskoa

Get client IP in Koa.js


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.


Solution

  • 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}`;
    })