In Koa.js, you can access the client's IP address through the request object (ctx.request). The most straightforward method is to use the ctx.request.ip property. However, in real-world deployments, many applications are placed behind a proxy (such as Nginx), where the directly obtained IP may be the proxy server's IP. To obtain the actual client IP, it is common to retrieve it via the X-Forwarded-For request header.
Here is a simple example demonstrating how to obtain the client's real IP address in Koa.js:
javascriptconst Koa = require('koa'); const app = new Koa(); // Trust proxy headers app.proxy = true; app.use(async ctx => { // Obtain the client's real IP address const clientIp = ctx.request.ip; // If using a proxy, you can retrieve the real IP as follows: // const xForwardedFor = ctx.request.header['x-forwarded-for']; // const realClientIp = xForwardedFor ? xForwardedFor.split(',')[0] : clientIp; ctx.body = `Your IP address is: ${clientIp}`; }); app.listen(3000, () => { console.log('Server is running on http://localhost:3000'); });
In the above code:
app.proxy = true;tells Koa to trust proxy headers (such asX-Forwarded-For), which is typically set when the application is deployed behind a proxy.ctx.request.ipis used to obtain the request's IP address. Whenapp.proxy = true;is set, Koa automatically considers theX-Forwarded-Forheader.- The commented lines demonstrate how to manually extract the client's real IP from the
X-Forwarded-Forheader. This may vary depending on deployment settings, as some proxies add multiple IP addresses to theX-Forwarded-Forheader.
Ensure to be cautious when setting app.proxy = true; in production environments, as it trusts the IP address in the request headers. Only set it when you are certain that the proxy is trustworthy and correctly configured. Incorrectly trusting proxy headers may lead to security vulnerabilities.