Express.js - get client IP address from request / req

4 points
Created by:

In this short article, we would like to show how to get a client IP address from a request (req argument) in Express.js server application.

Client IP Address for request in local network - Express.js server application
Client IP Address for request in local network - Express.js server application


  1. Integrate below code with your web site,
  2. Run your Express.js server application,
  3. Open one of the following addresses in the web browser:
    • http://localhost:3000/client-ip-address for localhost development,
    • for production.

request_ip_address.js file:

const IP_HEADERS = [
    'X-Forwarded-For',     // may contain multiple IP addresses in the format: 'client IP, proxy 1 IP, proxy 2 IP' - we use first one
    'X-Real-IP',           // Nginx proxy, FastCGI
    'X-Cluster-Client-IP', // Rackspace LB, Riverbed Stingray
    'CF-Connecting-IP',    // Cloudflare
    'Fastly-Client-Ip',    // Fastly CDN and Firebase hosting header when forwared to a cloud function
    'True-Client-Ip',      // Akamai and Cloudflare

    // you can add more matching headers here ...

const getRequestIpAddress = request => {
    const headers = request.headers;
    for (const header of IP_HEADERS) {
        const value = headers[header];
        if (value) {
            const parts = value.split(/\s*,\s*/g);
            return parts[0] ?? null;
    const client = request.connection ?? request.socket ??;
    if (client) {
        return client.remoteAddress ?? null;
    return null;

module.exports = {

index.js file:

const express = require('express');

const {getRequestIpAddress} = require('./request_ip_address');

const port = 3000;
const app = express();

app.get('/client-ip-address', (req, res) => {
    const ip = getRequestIpAddress(req);
    response.send(`Client IP Address: ${ip}`);

app.listen(port, () => {
    console.log(`Server is listening at ${port} port.`);

Note: IP_HEADERS are useful to get a client IP address when we use some other application that may cover our server, e.g. VirtualServers, load balancers, etc.


  1. request-ip - npm
  2. pbojinov/request-ip: A Node.js module for retrieving a request's IP address on the server - Github
Native Advertising
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂