Answer To : How To Create A Https Server Using Node.Js ?

Asked on November 01, 2023

In the previous blog we created the self-signed ssl certificate and the private key. In this part we will create a https server in Node.Js. But before we get started ensure that nodejs is installed in your system and the paths are included in the environment of your system

First we will create a nodejs app in our system. To do this we need to create a folder in any directory of your system where the project should be located.Next step is to create nodejs app with the help of a library called npm. To create it we need to open terminal/cmd and go to the project directory and type npm init and select the default values. And you are done with creating a noejs app. Now your project folder includes package.JSON file.

Now create a file with the name server.js in the root project folder

We will require few dependencies like express, https and fs to create an https server. We need to install these dependencies using npm through terminal

npm install express https fs --save

Now You can see a new folder name NODE_MODULES in the project directory. Next step is to open server.js file and load the required library that is to be used in creating a https server.

const express = require('express');
const https = require('https');
const fs = require('fs');

The next step to declare the key and certificates ( the created key and cerficate should be copied to the root project folder ) which we created previously to the variables like this :

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

And finally to create an https server using express and https. A variable is declared which calls the express() function and then using https.createServer and passing the options and app variable to it https server is created

var app = express();
https.createServer(options, app,function (request, response) {
  console.log("listening on https://localhost:3000");
}).listen(3000);
app.get('/', function(req,res) {
    res.end('hello');
});

Finally https server is generated using express and https library. To run the https server open cmd and go to the project directory and type the following code :

node server.js
output:

listening on https://localhost:3000

open the browser and go to https://localhost:3000 and you will see the message hello



Please sign in to post a comment