How to create HTTPS Server with Node.js ? - GeeksforGeeks

01 Oct, 2021
The HTTP protocol is one of the most important protocols for smooth communication between the networks but in the HTTP protocol, data is not encrypted so any sensitive information can be sniffed during the communication so there is another version of the HTTP i.e HTTPS that encrypts the data during the transmission between a browser and the server. In this article, we will discuss how we can create an HTTPS server using Node.js.
To built an HTTPS server with nodeJs, we need an SSL (Secure Sockets Layer) certificate. We can create a self-signed SSL certificate on our local machine. Let’s first create an SSL certificate on our machine first.
Step 1: First of all we would generate a self-signed certificate. Open your terminal or git bash and run the following command:
openssl req -nodes -new -x509 -keyout server.key -out server.cert
After running this command, we would get some options to fill. We can keep those options default or empty by entering ‘.‘ (dot). We would fill only two options for current as that would work fine for us.
Common Name (e.g. server FQDN or your name): localhost
Email Address : *************@****** (enter your email)
Other options such as Country Name, State or Province Name, Locality Name, Organization Name, and Organizational Unit Name are self-explanatory and also the system gives their example for help.
creating SSL Certificate
This would generate two files:
server.cert: The self-signed certificate file.
server.key: The private key of the certificate.
Step 2: Now let’s code the index.html file. We will create a form to send a message to the server through a POST request.
index.html
<!DOCTYPE html><html lang="en">  <head>    <meta charset="UTF-8">    <meta http-equiv="X-UA-Compatible" content="IE=edge">    <meta name="viewport" content        ="width=device-width, initial-scale=1.0">    <title>HTTPS Server</title></head>  <body>    <h1>Welcome to HTTPS Server</h1>    <br><br>    <h3>Enter your message</h3>      <!--  sending post request to "mssg" with         the message from the textarea -->    <form action="mssg" method="post">        <textarea name="message" id=""             cols="30" rows="10"></textarea>        <button type="submit">Send</button>    </form></body>  </html>
Step 3: Now create an app.js file. We would initialize the project using npm in the terminal
npm init
We would also install express for handling server requests and body-parser for taking input from the form in the POST request.
npm install express
npm install body-parser
Project Structure:
file structure
Step 4: Now we will code the app.js  file. In this file, we create an HTTPS server using createServer() function. We pass the certificate and key files of the SSL certificate as options object in createServer() function. We handle GET and POST requests using express in NodeJs.
app.js
// Requiring in-built https for creating// https serverconst https = require("https");  // Express for handling GET and POST requestconst express = require("express");const app = express();  // Requiring file system to use local filesconst fs = require("fs");  // Parsing the form of body to take// input from formsconst bodyParser = require("body-parser");  // Configuring express to use body-parser// as middle-wareapp.use(bodyParser.urlencoded({ extended: false }));app.use(bodyParser.json());  // Get request for root of the appapp.get("/", function (req, res) {    // Sending index.html to the browser  res.sendFile(__dirname + "/index.html");});  // Post request for geetting input from// the formapp.post("/mssg", function (req, res) {    // Logging the form body  console.log(req.body);    // Redirecting to the root  res.redirect("/");});  // Creating object of key and certificate// for SSLconst options = {  key: fs.readFileSync("server.key"),  cert: fs.readFileSync("server.cert"),};  // Creating https server by passing// options and app objecthttps.createServer(options, app).listen(3000, function (req, res) {  console.log("Server started at port 3000");});
Step 5: Run node app.js file using below command:
node app.js
Now open the browser and type the running server address:
https://localhost:3000/
Now you would see a webpage running with HTTPS. Write your message in the text area.
Web page view
Now hit the send button and see it in your console. The output would be:
Output in console
So, In this way, we can create an HTTPS server using Node.js
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
HTML-Questions
NodeJS-Questions
Picked
HTML
Node.js
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
HTML Cheat Sheet - A Basic Guide to HTML
Design a web page using HTML and CSS
Form validation using jQuery
Angular File Upload
Installation of Node.js on Linux
Node.js fs.readFileSync() Method
Node.js fs.writeFile() Method
Node.js fs.readFile() Method
How to update NPM ?