How to Create HTTPS Server with Node.js ?
Last Updated :
21 Jun, 2024
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 CertificateThis 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 structureThe 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 viewNow hit the send button and see it in your console. The output would be:
Output in consoleSo, 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 Create a Simple HTTP Server in Node?
NodeJS is a powerful runtime environment that allows developers to build scalable and high-performance applications, especially for I/O-bound operations. One of the most common uses of NodeJS is to create HTTP servers. What is HTTP?HTTP (Hypertext Transfer Protocol) is a protocol used for transferri
3 min read
How to Create and Verify JWTs with Node?
In this article, we will see how to create JWT tokens in Node.js. We will implement secure authentication in Node.js by creating and verifying JSON Web Tokens (JWTs) using libraries like `jsonwebtoken`.Prerequisites:Good knowledge of JavaScript.Basic knowledge about Express JS.Basic knowledge about
5 min read
How to Build a Simple Web Server with Node.js ?
Node.js is an open-source and cross-platform runtime environment for executing JavaScript code outside a browser. You need to remember that NodeJS is not a framework, and itâs not a programming language. Node.js is mostly used in server-side programming. In this article, we will discuss how to make
3 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 ins
2 min read
How to Connect to Telnet Server from Node.js ?
Connecting to a Telnet server from Node.js involves creating a client that can communicate using the Telnet protocol. Telnet is a protocol used to establish a connection to a remote host to execute commands and transfer data. In Node.js, you can use various packages to facilitate the connection to a
4 min read
How to Serve Static Content using Node.js ?
Accessing static files are very useful when you want to put your static content accessible to the server for usage. To serve static files such as images, CSS files, and JavaScript files, etc we use the built-in middleware in node.js i.e. express.static. Setting up static middleware: You need to crea
2 min read
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
5 min read
Node.js http.ServerResponse.socket Api
The httpServerResponse.socket is an inbuilt application programming interface of class ServerResponse within http module which is used to get the reference of the underlying socket object. Syntax: response.socket Parameters: This method does not accept any arguments as a parameter. Return Value: Thi
2 min read
How to Build a Node.js Proxy Server ?
A proxy server acts as an intermediary between a client and other servers. It can be used for various purposes, including load balancing, security, and caching. In the context of web development, a proxy server forwards requests from clients to other servers, fetches responses, and sends them back t
4 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 para
2 min read