ctx.request.ip
The remote IP address of the request; respects `X-Forwarded-For` when `app.proxy` is `true`.
Syntax
ctx.request.ip // or ctx.ip Returns
string — The client IP address string (IPv4 or IPv6).
Examples
import Koa from 'koa';
const app = new Koa();
app.proxy = true; // trust X-Forwarded-For from reverse proxy
app.use(async (ctx) => {
ctx.body = { clientIp: ctx.ip };
});
app.listen(3000);
Output
{"clientIp":"203.0.113.42"}
// Rate limiting by IP
const counts = new Map();
app.use(async (ctx, next) => {
const count = (counts.get(ctx.ip) ?? 0) + 1;
counts.set(ctx.ip, count);
if (count > 100) ctx.throw(429, 'Too Many Requests');
await next();
});
Output
101st request from same IP → 429 Too Many Requests
Notes
When `app.proxy = true`, Koa reads the first entry in the
`X-Forwarded-For` header. `ctx.ips` provides the full array of
forwarded IPs. Do not trust this value without `app.proxy = true` and
a correctly configured proxy.