The Wayback Machine - https://web.archive.org/web/20241113053946/https://www.geeksforgeeks.org/how-to-create-https-server-with-node-js/
Open In App

How to Create HTTPS Server with Node.js ?

Last Updated : 21 Jun, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.



Similar Reads

How to Configure Google Compute Engine to use HTTPS for Node.js Server ?
In this article, we will have a look at the configuration of HTTPS for the Node.js server deployed in Google Compute Engine. We will see how we can set up a Node.js server with reverse proxy with an NGINX server having HTTPS configuration.  We will use GCE (Google Compute Engine) Virtual machine for setting up our application. NGINX is a free web s
5 min read
How to detect HTTP or HTTPS then force redirect to HTTPS in JavaScript ?
HTTPS stands for Hypertext Transfer Protocol Secure. As its name implies, it creates a secure, encrypted connection between the user's browser and the server they are trying to access. Since it is an encrypted connection, it prevents malicious hackers from stealing data that is transmitted from the user's browser to the server. Having a site in HTT
3 min read
Node.js Automatic restart Node.js server with nodemon
We generally type following command for starting NodeJs server: node server.js In this case, if we make any changes to the project then we will have to restart the server by killing it using CTRL+C and then typing the same command again. node server.js It is a very hectic task for the development process. Nodemon is a package for handling this rest
1 min read
How to Redirect http to https in Apache Server?
Redirecting HTTP traffic to HTTPS ensures that all communications between your website and its visitors are securely encrypted. This is crucial for protecting sensitive information and maintaining the integrity of data. By configuring your Apache server to redirect HTTP to HTTPS, you enhance the security and trustworthiness of your users. Approach:
1 min read
How to create proxy server on Heroku in Node.js ?
The following approach covers how to create a proxy server on Heroku using NodeJS. Heroku is a cloud application platform that is used as PaaS (Platform as a service) to build, operate and run applications on their cloud. Prerequisites: To create a proxy server, you will need the following to be installed on your computer: Install Heroku CLI.Instal
2 min read
How to create a simple HTTP server in Node ?
NodeJS provides a straightforward way to create HTTP servers, allowing developers to build web applications and APIs without relying on external web servers like Apache or Nginx. Let's explore how to create a simple HTTP server in NodeJS. Steps to Create a NodeJS Server:Step 1: Initialize the NPM using the below command. Using this the package.json
1 min read
How to Create a Simple Server in Node.js that Display Hello World ?
We will create a simple server in Node.js that returns Hello World using an express server. Node.js is a powerful JavaScript runtime built on Chrome's V8 engine, commonly used to build scalable network applications. One of the fundamental tasks when learning Node.js is creating a simple server that responds with "Hello World." This article will gui
2 min read
Difference between Apache Tomcat server and Apache web server
Apache Tomcat server: Apache Tomcat is a web container. It allows the users to run Servlet and JAVA Server Pages that are based on the web-applications. It can be used as the HTTP server. The performance of the Tomcat server is not as good as the designated web server. It can be used as separate product with its own internal Web-server. It can also
2 min read
Difference between Web Server and Mail Server
Web Server : Web Server, as the name suggests, is a server software where web content is stored and uses HTTP protocol and other protocols to respond to user requests that is being made over WWW. Its main function is to display the content of the website through storing, processing, and delivering webpages within the website to users. Example: Apac
4 min read
How to install and configure Apache Web Server on Godaddy Server?
GoDaddy VPS is a shared server that provides computational services, databases, storage space, automated weekly backups, 99% uptime, and much more. It’s a cheaper alternative to some other popular cloud-based services such as AWS, GPC, and Azure. Apache HTTP Server is an open-source web server software widely used by web hosting companies to provid
2 min read
Server Side Rendering vs Client Side Rendering vs Server Side Generation
In the world of web development, there are several approaches to rendering web pages: server-side rendering, client-side rendering, and server-side generation. Each approach has its own advantages and disadvantages, and choosing the right one for your project depends on your specific needs and goals. In this blog, we’ll explore the differences betw
4 min read
How to Install Apache Web Server on Linux Cloud Server?
Apache is an open-source web server used widely for hosting websites and web applications. It's popular on the internet and supports platforms like Linux, Windows, and macOS. Installing Apache on a Linux-based cloud server is straightforward. Cloud servers offer flexibility and scalability, enabling easy management and deployment of computing resou
5 min read
Difference Between Web server and Application server
A server is a central repository where information and computer programs are held and accessed by the programmer within the network. Web servers and Application servers are kinds of servers employed to deliver sites and therefore the latter deals with application operations performed between users and back-end business applications of the organizat
3 min read
HTTPS in Node.js
HTTP: When the data is transferred in HTTP protocol it just travels in the clear text format. HTTPS: It simply encrypts the request from the browser to the web server, so it is tough to sniff that information. It basically works on two things: SSL (Secure Socket Layer)TLS (Transport layer security) Both of these use a PKI (Public Key Infrastructure
3 min read
HTTPS module error handling when disconnecting from internet in Node.js
When working with the HTTPS module in Node.js, it is possible to encounter an error when the internet connection is lost or disrupted while the HTTPS request is being made. This can cause the request to fail and throw an error, disrupting the normal flow of the application. Consider the following code example, which makes an HTTPS request to a remo
6 min read
Node.js https.request() Function
Https request function in Node is used to make the http request over secure http or https. It provide more control to the request like setting headers, http methods, adding request data and handle the responses. https.request(options, callback)It is a part of https module and allows to send different requests like GET, POST,, PUT, DELETE etc. to in
2 min read
Build a Simple static file web server in Node.js
In this article, we will build a static file web server which will list out all the files in the directory and on clicking the file name it displays the file content. Steps for creating a static file server is as follows: Step 1: Importing necessary modules, and defining MIME types which helps browser to understand the type of file that is being se
4 min read
How to Set Online SQL Server for Node.js ?
An Online SQL server helps to connect your project with an online server instead of localhost database setup. To achieve this, the remotemysql site is popular for providing an online database to store our data in a secure way. Installation of sql module: You can visit the link Install sql module. You can install this package by using this command.n
2 min read
Node.js Server Side Rendering (SSR) using EJS
Server-side rendering (SSR) is a popular technique for rendering a normally client-side-only single-page app (SPA) on the server and then sending a fully rendered page to the client. The client's JavaScript bundle can then take over and the SPA can operate as normal. SSR technique is helpful in situations where the client has a slow internet connec
3 min read
Node.js server.close() Method
The server.close() is an inbuilt application programming interface of class Socket within tls module which is used to stop the server from accepting the new client request. Syntax: const server.close() Parameters: This method does not accept any parameter. Return Value: This method return nothing but a callback function for listening the server ins
3 min read
Node.js server.address() Method
The server.address() is an inbuilt application programming interface of class Socket within tls module which is used to get the bound address of the server. Syntax: const server.address() Parameters: This method does not accept any parameter. Return Value: This method returns the bound address containing the family name, and port of the server. How
3 min read
Node.js server.getTicketKeys() Method
The server.getTicketKeys() is an inbuilt application programming interface of class Socket within tls module which is used to get a 48-byte buffer containing the session ticket keys. Syntax: const server.getTicketKeys() Parameters: This method does not accept any parameter. Return Value: This method returns a 48-byte buffer containing the session t
3 min read
Node.js server.setTicketKeys() Method
The server.setTicketKeys(keys) is an inbuilt application programming interface of class Socket within tls module which is used to set a 48-byte buffer containing the session ticket keys. Syntax: server.setTicketKeys(keys) Parameters: This method accepts the 48-byte buffer containing the session ticket keys as a parameter. Return Value: This method
4 min read
Node.js server.setSecureContext() Method
The server.setSecureContext() is an inbuilt application programming interface of class Socket within tls module which is used to replace the secure context for the existing server. Syntax: server.setSecureContext(options) Parameters: This method takes any of the possible properties from the tls.setSecureContext() options arguments. Return Value: Th
3 min read
Node.js server.addContext() Method
The server.addContext() is an inbuilt application programming interface of class Socket within tls module which is used to add the security context for the use of the client. Syntax: server.addContext(hostname, context) Parameters: This method takes the following argument as a parameter: hostname: A server name indicating hostname.context: Any of t
4 min read
Node.js server.listen() Method
The server.listen() is an inbuilt application programming interface of class Socket within tls module which is used to start the server to listen the encrypted connection. Syntax: const server.listen([port[, host[, backlog]]][, callback]) Parameters: This method takes the following argument as parameter: port: It is the port number. host: It's the
3 min read
Node.js http.server.close() Method
The http.server.close() is an inbuilt application programming interface of class Server within the HTTP module which is used to stop the server from accepting new connections. Syntax: const server.close([callback])Parameters: This method accepts only one optional callback function argument as a parameter. Return Value: This method returns nothing b
2 min read
Node.js http.server.headersTimeout Method
The http.server.headersTimeout is an inbuilt application programming interface of class Server within the HTTP module which is used to get the time the parser will wait to receive the complete HTTP headers. Syntax: server.headersTimeoutParameters: This method does not accept any arguments as a parameter. Return Value: This method returns time, the
2 min read
Node.js http.server.maxHeadersCount Property
The http.server.maxHeadersCount is an inbuilt application programming interface of class Server within the HTTP module which is used to get the maximum number of incoming headers to count. Syntax: const server.maxHeadersCountParameters: This property does not accept any argument as a parameter. Return Value: It does not return any value. Example 1:
3 min read
Node.js http.server.listening Property
The http.server.listening is an inbuilt application programming interface of class Server within http module which is used to check if the server is listening for connection or not. Syntax: const server.listening Parameters: It does not accept any argument as a parameter. Return Value: It does not return any value. Example 1: Filename: index.js C/C
3 min read
three90RightbarBannerImg