Skip to content

Enabling HTTPS for Express.js application

Last updated on February 25, 2017

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.

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments