How to create HTTPS Server with Node.js?


As the consumption of the cyberspace and cloud-dependent applications proliferates, the gravity of safeguarding online data and transactions becomes more apparent. One of the most commonly employed methodologies for securing online communications is HTTPS, which provides an assurance that the information conveyed between the server and clients is ciphered and cannot be effortlessly intercepted by malevolent third parties. In this manuscript, we will probe into the process of building an HTTPS server with Node.js, an influential and adaptable platform for developing server-side applications using JavaScript. We will go over the fundamentals of SSL certificates, the essential components of an HTTPS server, and furnish meticulous instructions for setting up a secure server using Node.js. Upon the termination of this manuscript, you will have the capacity and proficiency to fabricate your own impregnable HTTPS server, safeguarding your online data and ensuring the confidentiality of your users.

Syntax

http.createServer([options][, requestListener])

http.createServer is a method offered by the built-in Node.js http library that permits the developer to generate a HTTP server that can listen for incoming requests and dispatch responses back to the end-user.

This method requires two optional parameters −

Options (Object) − The configuration object is non-mandatory and can be utilized by the developer to customize the server’s actions according to their preferences.

requestListener (Function) − This is an optional callback function that will be invoked everytime an incoming HTTP request is detected. This function further takes two more arguments: the req (request) object and the res (response) object. The req object stores the particulars about the incoming request, such as the HTTP method, headers, and body. The res object is used to send a response back to the client, and it provides methods for setting response headers, status code, and sending response body.

Approach

In order to produce a HTTPS server utilizing Node.js, you will be required to perform a number of procedures. To begin with, it is of utmost necessity to produce an SSL certificate and private key. While you might choose an online service provider to undergo this, for the matter of this article I am going to use OpenSSL. OpenSSL is a software that allows users the prospect to generate a self-signed certificate using a command line. This certificate is primarily required to encrypt the communications between the server and client. Once you obtain the certificate and key files, it’s essential to create a fresh Node.js file and load the HTTPS module into it. Then, use the fs module to load the certificate and key files into memory. These files will be utilized as options when creating the HTTPS server instance. You may proceed with creating the HTTPS server by invoking the https.createServer() method and providing the said options as parameters. Now to enable the server to listen for incoming requests, invoke the listen() method and provide the required port number, along with an elective callback function. Once the server Is up and running, you can even manoeuvre the incoming requests by generating a request listener function. The req object holds data on the incoming request, while the res object sends a response back to the client.

Example

Before starting with the example, run the following command to generate the digitally signed certificate from OpenSSL.

openssl req -nodes -new -x509 -keyout server.key -out server.cert

The following is the complete code which we are going to look at in this example −

import { createServer } from "https";
import express from "express";
import { readFileSync } from "fs";
import pkg from "body-parser";
 
import path from 'path';
import {fileURLToPath} from 'url';
 
const app = express();
 
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
 
const { urlencoded, json } = pkg;
 
app.use(urlencoded({ extended: false }));
app.use(json());
 
const options = {
   key: readFileSync("server.key"),
   cert: readFileSync("server.cert"),
};

app.get("/", function (req, res) {
   res.sendFile("index.html",{root: __dirname})
});

createServer(options, app).listen(3001, function (req, res) {
   console.log("Server started at port 3001");
});

This piece of code is scripted in JavaScript, and it serves to construct an HTTP server that dispenses an HTML document. It brings in a handful of modules, which encompass the "createServer" technique from the "https" module, the "express" module, and the "readFileSync" procedure from the "fs" module.

The code defines an Express application object and sets up the necessary middleware for handling requests. The middleware includes the "urlencoded" function and the "json" function, which are used to parse request data in either URL-encoded or JSON format.

The script initializes the setup of the server, where the Secure Sockets Layer (SSL) key and certificate files are being established to guarantee a secure and ciphered communication between the server and clients. Following that, the function app.get() is utilized to manage the root URL path of the server. Whenever a GET request is received on the root URL, the function transmits an HTML file named "index.html" to the client. This file exists in the identical directory as the script file, and its location is derived through the utilization of the variable "__dirname".

Ultimately, the invocation of the "createServer" function engenders a novel HTTPS server entity, replete with the indicated options and app object. Upon instantiation, the server diligently attunes its receptors to the idiosyncratic frequency of port 3001, prompting an audio-visual notification to be emitted to the user through the console interface.

Output

Conclusion

To recapitulate, fabricating an HTTPS server using Node.js is a potent strategy to amplify the security of your web applications. By concocting and configuring SSL certificates, you can warrant that all transmission between your server and clients is coded and secure. With the suppleness and scalability of Node.js, generating an HTTPS server is an attainable and productive procedure that can aid in safeguarding your users' data and establishing faith in your website. By adhering to the procedures delineated in this article, you can confidently create an HTTPS server and relish the tranquility that comes with knowing your website is amply safeguarded.

Updated on: 07-Sep-2023

498 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements