[Fixed] nodejs express: hostname with port from the req object


Sometimes I want to sent a qualified URL in a mail from my node application. Or I would like to set the content of a phantom page object.

I get the full URL like this in my deployment setup.

'http://' + req.hostname + '/myapp'

However on the development machine this usually produces:

http://localhost/myapp instead off http://localhost:3000/myapp

I know how to get the port but I don’t want to use something like:

'http://' + req.hostname + ':' + port + '/myapp'

Which would produce nonsense like this in deploy behind a proxy.


Is there a smart way to get the hostname with port from the request object if the app runs outside a proxy?


What you are looking for is the X-Forwarded-For header. It is the safest way to get the original url if you are behind proxies, load balancers etc. Check if this exists in your request and if exists use it, otherwise use what you’ve already implemented.

This express source it will be helpful:

  • The value of req.hostname is derived from the value set in the
    X-Forwarded-Host header, which can be set by the client or by the

  • X-Forwarded-Proto can be set by the reverse proxy to tell the app
    whether it is https or http or even an invalid name. This value is
    reflected by req.protocol.

  • The req.ip and req.ips values are populated with the list of
    addresses from X-Forwarded-For.

Leave a Reply

(*) Required, Your email will not be published