node.jsexpressflooding

Is it worth it to use request-ip package for an express.js app instead of req.ip


I need to do a basic flooding control, nothing very sophisticated. I want to get source IP and delay the answer if they are requesting too many times in a short period. I saw that there is a req.ip field but also a package: https://www.npmjs.com/package/request-ip

What's the difference?


Solution

  • I suggest you to use the request-ip module, because it looks for specific headers in the request and falls back to some defaults if they do not exist.

    The following is the order it uses to determine the user ip from the request.

    1. X-Client-IP
    2. X-Forwarded-For header may return multiple IP addresses in the format: "client IP, proxy 1 IP, proxy 2 IP", so we take the the first one.
    3. CF-Connecting-IP (Cloudflare)
    4. Fastly-Client-IP (Fastly CDN and Firebase hosting header when forwared to a cloud function)
    5. True-Client-IP (Akamai and Cloudflare)
    6. X-Real-IP (nginx proxy/FastCGI)
    7. X-Cluster-Client-IP (Rackspace LB, Riverbed Stingray)
    8. X-Forwarded, Forwarded-For and Forwarded (Variations of #2)
    9. appengine-user-ip (Google App Engine)
    10. req.connection.remoteAddress
    11. req.socket.remoteAddress
    12. req.connection.socket.remoteAddress
    13. req.info.remoteAddress
    14. Cf-Pseudo-IPv4 (Cloudflare fallback)
    15. request.raw (Fastify)

    It permits to get the real client IP regardless of your web server configuration or proxy settings, or even the technology of the connection (HTTP, WebSocket...)

    You can also take a look to the express req.ips (yes, ips, not req.ip) property to get more informations about the request:

    req.ips (http://expressjs.com/en/api.html)

    When the trust proxy setting does not evaluate to false, this property contains an array of IP addresses specified in the X-Forwarded-For request header. Otherwise, it contains an empty array. This header can be set by the client or by the proxy.

    For example, if X-Forwarded-For is client, proxy1, proxy2, req.ips would be ["client", "proxy1", "proxy2"], where proxy2 is the furthest downstream.