Home > Software engineering >  Nodejs security best practice regarding string values
Nodejs security best practice regarding string values

Time:11-01

I need to get the IP address using nodejs/express. Below is the statement I use for this.

const ipAddress = String(req.ip || "unknown");

Since req.ip originates from an HTTP header, a malicious user could change it. Is this then the best way to get the user's IP address?

CodePudding user response:

I suppose how "secure" it is depends on what you are trying to secure against.

Generally an IP should be considered transient - users on mobile can enter or exit wifi or different cell towers, and their IP can change. IPs can also be spoofed.

If you are using Express, req.ip does NOT normally come from a header but from the connection itself. The exception is if you are using a reverse proxy -- are you? In which case we'll need more details about the proxy being used and your proxy setup. Proxies should be configured to always overwrite the X-Forwarded-For sent by the client, such that the header can always be trusted.

CodePudding user response:

Here's the code I changed the above to:

let ipAddress = "";
if (req.ip === undefined) ipAddress = "unknown";
else ipAddress = String(req.ip);
  • Related