📍 A Lightweight Utility for Extracting the Real Client IP Address from Incoming HTTP Requests
npm install get-client-ip
A Lightweight Utility for Extracting
the Real Client IP Address from
Incoming HTTP Requests
get-client-ip? 🤔bash
npm install get-client-ip@latest
or
yarn add get-client-ip@latest
or
pnpm install get-client-ip@latest
or
bun add get-client-ip@latest
`
Usage 🪛
$3
`typescript
import http from "node:http";
import express from "express";
import { getClientIp } from "get-client-ip";
import { env } from "./env";
function bootstrap() {
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// Standalone usage:
app.get("/standalone-ip", (req, res) => {
const ip = getClientIp(req);
res.status(200).json({ ip });
});
// Middleware usage:
app.get("/middleware-ip", getClientIp, (req, res) => {
res.status(200).json({ ip: req.clientIp, ips: req.clientIps });
});
http.createServer(app).listen(env.PORT || 3000, () => {
console.log(🚀 Express server running on: http://localhost:${env.PORT || 3000});
});
}
bootstrap();
`
$3
`typescript
import { Controller, Get, Req } from "@nestjs/common";
import type { Request } from "express";
import { getClientIp } from "get-client-ip";
@Controller("")
export class PublicController {
@Get("ip")
getIp(@Req() req: Request) {
const ip = getClientIp(req);
return { ip };
}
}
`
Headers ⛑️
The following headers are checked in order of precedence:
`typescript
x-client-ip
x-forwarded-for
forwarded-for
x-forwarded
forwarded
x-real-ip
cf-connecting-ip
true-client-ip
x-cluster-client-ip
fastly-client-ip
x-appengine-user-ip
cf-pseudo-ipv4
`
It also falls back to:
`typescript
req.ip;
req.socket.remoteAddress;
req.connection.remoteAddress;
``