Node HTTPS Module: Creating an HTTPS Secure Server in Node.js

The HTTPS server in Node.js can be created using the HTTPS default module. HTTPS servers provide additional security by encrypting data that is being transmitted from a server to a client, plus it uses SSL/TLS certificates to verify the client. If you want to create a website using Node.js, HTTPS also helps you with SEO as search engines give more importance to websites using HTTPS in search rankings. 

In this tutorial we will start with an introduction to HTTPS, then the working of HTTPS, and then we will learn how to create an HTTPS server by creating a self-signed SSL certificate. We will also learn to make different types of requests to the HTTPS server such as GET, POST, PUT, etc. So that being said, let’s get started.

Introduction to 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 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 important 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 implementing 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.  However, all the actual data being exchanged is encrypted securely by the TLS/SSL protocol, along with: 

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

Getting Started with the Node HTTPS Module 

For using HTTPS in Node.js we first have to include it in the project which can be done by using the require() method.

Syntax:

Below is the syntax to import the HTTPS module.

const https = require('https'); 

Since it is a pre-built package we don’t need to install it manually, we can directly import it.

Creating a Self-Signed SSL Certificate 

To create a secure HTTPS server, we first have to create a self-signed SSL certificate.

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, run the following commands in the command line: 

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

Now you should find two files, one cert.pem, which is the certificate and key.pem, which is the private key. These files need to be stored 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 https = require('https');

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}`);
});

Using fs.readFileSync 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 object contains the HTTPS request details. We access the request headers and request data via req. 
  • res or response object will hold the data we return to the client. 

In the callback, we have set a statusCode of 200, to specify 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 the HTML code to res.write(). 

Run the Application:

We can now test if our server is properly set, by running our app by executing the below command in the terminal.

node index.js

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

Making Requests with Node.js HTTPS Module

The HTTPS module can also be helpful in making different types of requests to the server, such as GET requests, POST requests, DELETE requests, PUT requests, etc. 

Let’s first see how to make a GET request using it.

Making a GET Request 

const https = require('https');

const options = {
  hostname: 'yourapp.com',
  port: 443,
  path: '/about',
  method: 'GET'
};

const req = https.request(options, res => {
  console.log(`statusCode: ${res.statusCode}`);
  
  res.on('data', d => {
    process.stdout.write(d);
  });
});

req.on('error', error => {
  console.error(error);
});

req.end();

Here you have to replace ‘yourapp.com’ with the actual host name of the server, to which you want to make the GET request.

Making a POST Request 

In the same way as above, one can also make a POST request using the HTTPS module. 

const { TextEncoder } = require('util');
const https = require('https');

const data = new TextEncoder().encode(
  JSON.stringify({
    about: 'We sell milk 🍼'
  })
);

const options = {
  hostname: 'yourapp.com',
  port: 443,
  path: '/about',
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Content-Length': data.length
  }
};

const req = https.request(options, res => {
  console.log(`statusCode: ${res.statusCode}`);

  res.on('data', d => {
    process.stdout.write(d);
  });
});

req.on('error', error => {
  console.error(error);
});

req.write(data);
req.end();

The above code makes a POST request containing a JSON payload ({ about: ‘We sell milk 🍼’ }), which is encoded using TextEncoder() to convert it to binary data.

Making a PUT Request 

In the same way, you can make a PUT request as well.

const https = require('https');

const options = {
  hostname: 'yourapp.com',
  port: 443,
  path: '/resource',
  method: 'PUT'
};

const req = https.request(options, res => {
  console.log(`statusCode: ${res.statusCode}`);
  
  res.on('data', d => {
    process.stdout.write(d);
  });
});

req.on('error', error => {
  console.error(error);
});

req.end();

Making a DELETE Request 

You can see in all the above codes that the method property of the options object is changed according to the type of request. You can change it to the desired request, for a DELETE request change it to DELETE.

const https = require('https');

const options = {
  hostname: 'yourapp.com',
  port: 443,
  path: '/resource',
  method: 'DELETE'
};

const req = https.request(options, res => {
  console.log(`statusCode: ${res.statusCode}`);
  
  res.on('data', d => {
    process.stdout.write(d);
  });
});

req.on('error', error => {
  console.error(error);
});

req.end();

Conclusion 

The Node.js HTTPS module not only helps you create HTTPS-secure web servers but also lets you make requests to other servers and APIs. There are several things we’ve learned in this tutorial that may sound complicated at first, but definitely become easier if you give it a try. So when you are creating a server, don’t forget to secure it using the HTTPS module.

Reference

HTTPS Module – Node.js Official Documentation

Aneesha S
Aneesha S
Articles: 172