Languages
[Edit]
EN

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

4 points
Created by:
Fletcher-Peralta
418

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

Steps:

  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,
    • https://my-domain.com:3000/client-ip-address for production.

request_ip_address.js file:

const IP_HEADERS = [
    'Forwarded',
    'Forwarded-For',
    'X-Forwarded',
    'X-Forwarded-For',     // may contain multiple IP addresses in the format: 'client IP, proxy 1 IP, proxy 2 IP' - we use first one
    'X-Client-IP',
    'X-Real-IP',           // Nginx proxy, FastCGI
    'X-Cluster-Client-IP', // Rackspace LB, Riverbed Stingray
    'Proxy-Client-IP',
    '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
    'WL-Proxy-Client-IP',
    'HTTP_X_FORWARDED_FOR',
    'HTTP_X_FORWARDED',
    'HTTP_X_CLUSTER_CLIENT_IP',
    'HTTP_CLIENT_IP',
    'HTTP_FORWARDED_FOR',
    'HTTP_FORWARDED',
    'HTTP_VIA',
    'REMOTE_ADDR'

    // 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 ?? request.info;
    if (client) {
        return client.remoteAddress ?? null;
    }
    return null;
};

module.exports = {
    getRequestIpAddress
};

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.

References

  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.

❤️💻 🙂

Join