HTTPS in Node.js - GeeksforGeeks

14 Oct, 2021
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. It basically works on two things:  
SSL (Secure Socket Layer)
TLS (Transport layer security)
Both of these use a PKI (Public Key Infrastructure)  
If you can’t afford an SSL Certificate then the other alternative is that there are a lot of payment service that can provide you an API to integrate in your website i.e you can have your website on a non secure channel (HTTP) and whenever there is a payment then just redirect the user to that payment gateway service.
HTTPS is a separate module in Node.js and is used to communicate over a secure channel with the client. HTTPS is the HTTP protocol on top of SSL/TLS(secure HTTP protocol).
There are various advantages to this additional layer:  
Integrity and Confidentiality are guaranteed, as the connection is encrypted in an asymmetric manner.
We get authentication by having keys and certificates.
An Example to setup HTTPS server with Node.Js is as follows:  
We will first create an homepage.html file, this homepage.html file will have an HTML code of creating a web page i.e the page that will be displayed when the user asks for it or enter the URL of the same.
homepage.html file will also have a resource homepage.css
When the browser tries to get the resource homepage.css it will throw it to the server, the server will create a response header, so the browser knows how to parse the file.
The code shown below is written in a third file saved as .js file.
 
javascript
<script>(function() {   // Reading and writing to files in Node.js// working with directories or file systemvar fs = require("fs");      // Responsible for creating HTTPS server// taking options for the server// options like where your certificates // and private key files are located// also take actual request and response server// code for parsing web pages from filesvar https = require("https");   // Helps with mimetypes in creating our response headervar path = require("path");    // "text/css" is added in response header // so browser knows how to handle it var mimetypes = {    "css":"text/css",    "html":"text/html"};   // Options is used by the servers// pfx handles the certificate filevar options = {    pfx: fs.readFileSync("ssl/cert.pfx"),    passphrase: "encrypted"};   var server = https.createServer(options, function(request, response) {       // If the url is empty    if (request.url == "" || request.url == "/") {        request.url = "homepage.html";    }          // __dirname is the directory where we are getting    // these files from __dirname holds the file route    // request.url is the index.html we made earlier    // function is the callback function that holds two    // parameters    fs.readFile(__dirname + "/" + request.url, function(err, content) {        if (err) {             console.log("Error: " + err);        }         else {                    // 200 is code for OK            // content-Type is the object or the content header            response.writeHead(200,     {'Content-Type':mimetypes[path.extname(request.url).split(".")[1]]});            response.write(content);         }                      // This will send our response back to the browser        response.end();    });});     server.listen("port number", "IP Address", function() {       console.log("Server has started!");});    })();</script>
Output: Whatever the port number and IP Address is given to the server.listen it will execute that only web page whenever requested. And this web page will be an HTTPS. 
kashishsoda
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between dependencies, devDependencies and peerDependencies
Mongoose Populate() Method
Node.js Export Module
Mongoose find() Function
How to connect Node.js with React.js ?
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript