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

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.

That being said, for your use case it would be quicker to use Express' req.protocol property, which is either http or https. Note, however, that for outgoing links, you can just refer to //example.com/path, and the browser will use the current protocol. (See also Can I change all my http:// links to just //?)

For node Request object without Express:

It's in req.connection.secure (boolean).

Edit: The API has changed, 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');