Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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; 
like image 375
aartiles Avatar asked Apr 27 '12 10:04

aartiles


People also ask

How do I know if my request is HTTP or HTTPS?

Approach 1: Check if the connection is using SSL and if the value of $_SERVER['HTTPS'] is set, then we can say that the connection is secured and called from 'HTTPS'. If the value is empty, this means the value is set to '0' or 'off' then we can say that the connection is not secured and the page is called from 'HTTP'.

What is the difference between HTTP and HTTPS in NodeJS?

js. HTTP: When the data transfer in HTTP protocol it just travels in the clear text format. HTTPS: It simply makes encryption when the request is traveling from the browser to the web server so it is tough to sniff that information.

What is HTTPS request in NodeJS?

Node. js provides two core modules for making http requests. The http module can be used to make http requests and the https module can be used to make https requests. One great feature of the request is that it provides a single module that can make both http and https requests.


1 Answers

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.

like image 116
Linus Thiel Avatar answered Sep 28 '22 11:09

Linus Thiel