How to know if a request is http or https in node.js

I am using nodejs and expressjs. I wonder if there is something like request.headers.protocol in the clientRequest object. I would like to build the baseUrl for the web links. So if the request was done via https I would like to keep https in all links.

    var baseUrl = request.headers.protocol + request.headers.host;

Edit: For Express, it's safer and recommended to use req.secure (as @Andy recommends below). While it uses a similar implementation, it will be safe for future use and it also optionally supports the X-Forwarded-Proto header.

Edit: My previous answer was incorrect - the API has changed. This is for Node 0.6.15:

An HTTPS connection has req.connection.encrypted (an object with information about the SSL connection). An HTTP connection doesn't have req.connection.encrypted.

Also (from the docs):

With HTTPS support, use request.connection.verifyPeer() and request.connection.getPeerCertificate() to obtain the client's authentication details.

req.secure is a shorthand for req.protocol === 'https' should be what you looking for.

If you run your app behind proxy, enable 'trust proxy' so req.protocol reflects the protocol that's been used to communicate between client and proxy.

app.enable('trust proxy');

You don't need to specify the protocol in URL, thus you don't need to bother with this problem.

If you use <img src="//mysite.comm/images/image.jpg" /> the browser will use HTTP if the page is served in HTTP, and will use HTTPS if the page is served in HTTPS. See the @Jukka K. Korpela explanation in another thread.

This worked for me:

req.headers['x-forwarded-proto']

Hope this helped,

E