Categories
Express.js

Enabling HTTPS for Express.js application

By using HTTPS protocol we increase the security of your application, SSL mechanism will encrypt the connection between you and your application server, data will be travel in secure layer. To use SSL certificates in your application you have to purchase it form authorized certificate providers like Godaddy.com or you can install your own self signed certificate, however there are some limitations with self signed certificates( generally browser don’t recognize it).

Once you got access to (purchase or self singed) certificates, download .key and .cert files and name it as wish.

Now, let’s use the native https module to allow our server to start using the HTTPS protocol and the fs module to read the downloaded files arjunphp.key and arjunphp.cert to be used as credential parameters to start our server in HTTPS mode.

Use Express with HTTPS

Below script will create Express application running over HTTPs.

   const fs = require('fs');
   const https = require('https');
   const express = require('express');
   const app = express();
    
    // create https server by passing key and cert files.
    https.createServer({
      key: fs.readFileSync('arjunphp.pem'),
      cert: fs.readFileSync('arjunphp.pem')
    }, app).listen(8080);

    app.get('/', function (req, res) {
      res.header('Content-type', 'text/html');
      return res.end('

Secure page!

'); });

To run the https server, issue following command

$ node server.js

Now head over to https://localhost:8080. You will get “Secure page!” page content.

By Praveen Anaparthi

11+ years of IT industry experience holding a wide range of skill sets and roles with significant work on PHP, Node.js, Python, Ruby, Docker, React.js, Microsoft Azure, Azure DevOps, Windows PowerShell, Shell script, Jenkins, MongoDB, SQL, MySQL, Apache, Nginx. etc. It is my passion to learn new things and implement them as a practice. Aside from work, I like gardening and spending time with pets.

Leave a Reply

Your email address will not be published.