9

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.

http://domain.com:3000/myapp

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

Dennis Bauszus
  • 1,624
  • 2
  • 19
  • 44

2 Answers2

11

I'm not sure why Express Request deprecated host, but this is a safe bit of code to overcome the issue of running an Express server behind/not behind a proxy.

const proxyHost = req.headers["x-forwarded-host"];
const host = proxyHost ? proxyHost : req.headers.host;

(Where I have found this most handy is constructing "return to" URLs for workflows involving redirects eg: OAuth 2)

Michel Floyd
  • 18,793
  • 4
  • 24
  • 39
kierans
  • 2,034
  • 1
  • 16
  • 43
3

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 proxy.

  • 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.

Stavros Zavrakas
  • 3,045
  • 1
  • 17
  • 30
  • 4
    Yes. I am doing this. As mentioned. In deploy everythings works as it should be. The problem only exists on my development platform. So at the moment I have localhost:3000 hardcoded and then switch comments before I push to version control. It's working but it's not elegant, hence the question whether there is something smarter possible to get this working in localhost development just like it will work in deploy. – Dennis Bauszus Oct 06 '16 at 11:02