get-client-ip
Version:
📍 A Lightweight Utility for Extracting the Real Client IP Address from Incoming HTTP Requests
51 lines (48 loc) • 1.86 kB
TypeScript
import { Request, Response, NextFunction } from 'express';
type NoneEmptyArray<T> = [T, ...T[]];
/**
* Extracts the client's IP address from an incoming Express request.
*
* This function works both as a standalone utility and as Express middleware.
* It attempts to detect the IP by inspecting common proxy-related headers
* such as `x-forwarded-for`, `x-real-ip`, and others. If no valid IP is found
* in the headers, it falls back to `req.socket.remoteAddress` or `req.connection.remoteAddress`.
*
* When used as middleware, it populates:
* - `req.clientIp`: The first valid IP address found.
* - `req.clientIps`: A non-empty array of all valid IPs found.
*
* @param req - The Express request object.
* @param res - (Optional) The Express response object. Included to support middleware signature.
* @param next - (Optional) The next function in the Express middleware chain.
*
* @returns The first detected client IP address as a string, or `undefined` if none is found.
*
* @throws Will throw an error if the `req` argument is not defined.
*
* @example
* // Standalone usage:
* app.get('/standalone-ip', (req, res) => {
* const ip = getClientIp(req);
* res.status(200).json({ ip });
* });
*
* @example
* // Middleware usage:
* app.use(getClientIp);
* app.get('/middleware-ip', (req, res) => {
* res.status(200).json({ ip: req.clientIp, ips: req.clientIps });
* });
*/
declare function getClientIp(req: Request, res?: Response, next?: NextFunction): string | undefined;
declare global {
namespace Express {
interface Request {
/** The first IP address extracted from the request headers */
clientIp?: string;
/** The array of all IP addresses extracted from the request headers */
clientIps?: NoneEmptyArray<string>;
}
}
}
export { getClientIp };