Enable HTTPS on express.js

Welcome to this comprehensive tutorial on setting up HTTPS in your Express.js application. In today’s digital world, securing your web application is not just a feature but a necessity. This guide will walk you through the process of enabling HTTPS, ensuring your Express.js app communicates over a secure channel.

What is HTTPS?

Before diving into the technicalities, let’s understand what HTTPS is. HTTPS (HyperText Transfer Protocol Secure) is an extension of HTTP. It is used for secure communication over a computer network and is widely used on the Internet. In HTTPS, the communication protocol is encrypted using Transport Layer Security (TLS) or, formerly, Secure Sockets Layer (SSL). This means that the data transferred between your server and your clients is encrypted and thus more secure.

Now, have a look at the methods below to enable HTTPS on express.js.

Generating Self-Signed SSL Certificate for Development

For development purposes, you can use a self-signed SSL certificate. Here’s how to generate one.

Open your terminal and run the following OpenSSL command to create a private key and a public certificate.

sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout selfsigned.key -out selfsigned.crt

Fill in the Details

Provide the necessary information such as your Country, State, Locality, Organization Name, etc.

Restart Your Express.js Server

After generating the certificates, restart your server to apply these changes.

Basic HTTPS Setup

Now that you have your SSL certificate and key, let’s set up HTTPS in your Express.js app.

Creating a Simple Express.js App

If you haven’t already, initialize a new Node.js project and install Express.js with the below commands.

mkdir my-secure-app && cd my-secure-app
npm init -y
npm install express

Adding HTTPS

Modify your app.js to include both HTTP and HTTPS protocols.

Create a new Express.js application or navigate to your existing project and a new file https-server.js then add the following code.

Example

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

var key = fs.readFileSync(__dirname + '/selfsigned.key');
var cert = fs.readFileSync(__dirname + '/selfsigned.crt');
var options = { key: key, cert: cert };

var app = express();
app.get('/', (req, res) => {
   res.send('Now using https..');
});

var server = https.createServer(options, app);
server.listen(port, () => {
   console.log("Server starting on port : " + port)
});

Run your Express.js application.

node https-server.js

Open your browser and go to https://localhost:3000. You might see a security warning because of the self-signed certificate. Proceed to view your secure Express.js application.

Redirecting HTTP to HTTPS

Modify your https-server.js to include HTTP and HTTPS servers.

const http = require('http');

//...[previous HTTPS setup code]

http.createServer(function (req, res) {
   res.writeHead(301, { "Location": "https://" + req.headers['host'] + req.url });
   res.end();
}).listen(80);

//...[HTTPS server code]

This code will create an HTTP server that redirects all traffic to your HTTPS server.

Using Let’s Encrypt for SSL in Production

For production environments, it’s recommended to use a trusted CA like Let’s Encrypt.

Install Greenlock-Express

npm install greenlock-express

Configure Greenlock-Express

Set up Greenlock-Express in your server file to manage SSL certificates.

// Include Greenlock-Express
var greenlock = require('greenlock-express').create({
  version: 'draft-11',
  server: 'https://acme-v02.api.letsencrypt.org/directory',
  email: '[email protected]',
  agreeTos: true,
  approveDomains: ['example.com', 'www.example.com'],
  app: app
});

// Listen on HTTP and HTTPS
greenlock.listen(80, 443);

Replace 'example.com' with your domain name.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top