Open In App

How to Create HTTPS Server with Node.js ?

Last Updated : 21 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Creating an HTTPS server in Node.js ensures secure communication between your server and clients. HTTPS encrypts data sent over the network, providing a layer of security essential for handling sensitive information. This guide will walk you through the process of setting up an HTTPS server in Node.js.

Approach

To build 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.

Steps to Create HTTPS Server with Node.js

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: 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: Iinitialize the project using npm in the terminal

npm init

Step 4: Install the necessary packages/libraries in your project using the following commands.

npm install express
npm install body-parser

Project Structure:

file structure

The updated dependencies in package.json file will look like:

"dependencies": {
"body-parser": "^1.20.2",
"express": "^4.19.2",
},

Example: In this example, 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.

JavaScript
// app.js

// Requiring in-built https for creating
// https server
const https = require("https");

// Express for handling GET and POST request
const express = require("express");
const app = express();

// Requiring file system to use local files
const fs = require("fs");

// Parsing the form of body to take
// input from forms
const bodyParser = require("body-parser");

// Configuring express to use body-parser
// as middle-ware
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

// Get request for root of the app
app.get("/", function (req, res) {

    // Sending index.html to the browser
    res.sendFile(__dirname + "/index.html");
});

// Post request for geetting input from
// the form
app.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 SSL
const options = {
    key: fs.readFileSync("server.key"),
    cert: fs.readFileSync("server.cert"),
};

// Creating https server by passing
// options and app object
https.createServer(options, app)
    .listen(3000, function (req, res) {
        console.log("Server started at port 3000");
    });

Step to Run Application: Run the application using the following command from the root directory of the project

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

Using a Trusted Certificate Authority (CA)

For production, use certificates from a trusted CA like Let’s Encrypt. You can automate certificate issuance and renewal using tools like Certbot. Replace the self-signed certificates in the example with the ones provided by your CA.

Handling Certificate Renewal

If you’re using certificates that expire (like those from Let’s Encrypt), ensure you have a process in place to renew and replace them before they expire. Automating this process reduces the risk of downtime due to expired certificates.

Conclusion

Setting up an HTTPS server in Node.js is straightforward and essential for securing web applications. By following the steps outlined in this guide, you can create a secure server that encrypts data between your server and clients, ensuring privacy and integrity. Whether using self-signed certificates for development or trusted CA certificates for production, implementing HTTPS is a crucial step in modern web development.



Next Article

Similar Reads