Node.js HTTPS: Quick & Easy Guide

In this Node.js tutorial, I will be covering the Node.js HTTPS built-in module for you. The HTTPS module in Node.js helps in transferring data securely via the HTTP TLS/SSL protocol. 

We will discuss in detail what HTTP is, how to get started with an HTTP server, and then easily sending and receiving HTTP requests through that server. 

What is HTTPS? 

HTTPS is short for Hypertext Transfer Protocol Secure, an extension of the Hypertext Transfer Protocol or HTTP, and is a more secure version of it. It is used widely on the internet, for secure communication over a computer network. 

HTTPS uses the TLS or Transport Layer Security encryption protocol, which was formerly known as Secure Sockets Layer or SSL.  

The encryption protocols of HTTPS give the ability to users on the web, to transfer or pass on sensitive information such as credit card numbers, banking information, login credentials, and more in a secure way. 

With these prominent features, HTTPS plays an eminent role in securing activities online like shopping, banking, and remote jobs. It has become so popular that all websites, whether they exchange sensitive data or not with users, are acquiring it. 

How does HTTPS Work? 

HTTPS wraps HTTP inside the SSL/TLS protocol to add encryption, so that all messages are encrypted in both directions i.e., between a client and a server. 

An eavesdropper may still be able to get access to information like IP Addresses, duration of sessions, port numbers, and domain names, all of the actual data being exchanged is encrypted securely by TLS/SSL protocol, along with: 

  • Headers 
  • Cookies 
  • Website Content 
  • Request URL 
  • Query parameters 

Getting Started with the Node.js HTTPS module 

To get started with HTTPS in Node.js, we will first need to include it in our project: 

const https = require(‘https’); 

Creating a Self-Signed SSL Certificate 

To create the secure, HTTPS server, we can start by creating a self-signed SSL certificate for ourselves. Speaking of SSL certificates, they are two kinds; those signed by a ‘Certified Author’, also known as CA, and those that are ‘self-signed’. 

A CA-signed certificate allows your users to trust the identity of your website and is recommended for the production environment. For testing or development purposes, a self-signed certificate will do just fine. 

Or, you could also choose to not create any certificate too, for which you can proceed with an HTTP server. 

To create a self-signed certificate, use this code in your terminal: 

openssl genrsa -out key.pem

openssl req -new -key key.pem -out csr.pem

openssl x509 -req -days 9999 -in csr.pem -signkey key.pem -out cert.pem

rm csr.pem

Okay, so now you should find two files, one cert.pem, which is the certificate and key.pem, which is the private key. Now, these files need to be under the same directory where your server file will reside. With this, you now have an SSL connection ready. 

Building an HTTPS Server 

Let us now set up our HTTPS Server, where we will send a ‘Hey there, your HTTPS Server is Live!’ message. The main difference between HTTPS & HTTP is the options variable. 

Make sure you have imported the HTTPS module into your project. 

const fs = require('fs');

const port = 8080;

const options = {  key: fs.readFileSync('key.pem'),

  cert: fs.readFileSync('cert.pem')

};

https.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.write('Hey there, your HTTPS Server is Live!');
  res.end();
}).listen(port, () => {

  console.log(`App running on Port: ${port}`);

});

When using fs.readFileSync, it will force the server to deal with requests one at a time and block the entire process until it completes. Sync forms aren’t a problem when loading crucial configuration data, like this one. 

Hence, on a busy server, it is advisable you go for the non-sync form, that is fs.readFile

  • req or request contains the HTTPS request details. We access the request headers and request data via req. 
  • res or response will hold the data we return to the client. 

We have set a statusCode of 200, to indicate a successful response. Click here to learn how to Handle the HTTP Status Code like a PRO!

We have also set our headers to ‘Content type’: ‘text/plain’, which indicates plain text on the webpage. Had it been ‘text/html’, we could pass HTML code to res.write(). 

We can now test if our server is properly set, by running our app: 

node index.js

Now, if everything looks good, you can jump to the next steps. 

Making Requests with Node.js HTTPS: GET, POST, PUT, DELETE 

Making HTTP requests in Node.js is simple and easy. Simply copy the code below and tweak it as per your choice! 

Make sure you have included https via the require module. 

Making a GET Request 

const options = {<br>hostname: 'yourapp.com',<br>port: 443,<br>path: '/about',<br>method: 'GET'<br>}<br><br>const req =https.request(options, res =&gt; {<br>console.log(`statusCode: ${res.statusCode}`)<br><br>res.on('data', d =&gt; {<br>process.stdout.write(d)<br>})<br>})<br><br>req.on('error', error =&gt; {<br>console.error(error)<br>})<br><br>req.end()

Making a POST Request 

const data = newTextEncoder().encode(<br>JSON.stringify({<br>about: 'We sell milk 🍼'<br>})<br>)<br><br>const options = {<br>hostname: 'yourapp.com',<br>port: 443,<br>path: '/about',<br>method: 'POST',<br>headers: {<br>'Content-Type': 'application/json',<br>'Content-Length':data.length<br>}<br>}<br><br>const req =https.request(options, res =&gt; {<br>console.log(`statusCode: ${res.statusCode}`)<br><br>res.on('data', d =&gt; {<br>process.stdout.write(d)<br>})<br>})<br><br>req.on('error', error =&gt; {<br>console.error(error)<br>})<br><br>req.write(data)<br>req.end()

Making a PUT & DELETE Request 

You must have noticed in the previous code snippets above, the options.method. Simply change its value as per your need for a PUT or DELETE request. 

Conclusion 

HTTPS is also known as Hypertext Transfer Protocol Secure is an extension of the Hypertext Transfer Protocol or HTTP, and is more secure than the latter. The built-in HTTPS module in Node.js helps in transferring data securely via the HTTP TLS/SSL protocol. 

Noteworthy References 

Aneesha S
Aneesha S
Articles: 174