Enable HTTPS in Node.js Express Application

    Apr 12, 2019       by Pankaj Kumar

No matter, In which side you are—being the user of a website or developing your own site—a good online experience tends to involve an authenticated third party and good encryption.

By using HTTPS, We can increase the security of our application, SSL mechanism will encrypt the connection between the user and application server. Data will be transferred in encoded format.

After purchasing certificate from any of the platform like Godaddy, Globehost or other service provider. We get .pem key and .cert file while installing it over our hosting server. So once certificate is installed is installed properly over the hosting server then we need to make changes in our application to convert the api from http to https url.

Now, we will use the native https module to allow our server to start using the HTTPS protocol and the fs module to read the downloaded files jsonworld.key and jsonworld.cert to be used as credential parameters while starting our server in HTTPS mode.

 

Let's have on code below:

 

const fs = require("fs");
const options = {
    key: fs.readFileSync('jsonworld.key').toString(),
    cert: fs.readFileSync('jsonworld.crt').toString()
};
 
const app = require('express')();
const server = require('http').Server(app);
 
server.listen(3000,()=>{
console.log('app listening on port: 3000');
});

 

Run the app with command, node app.js.

Now head over to https://localhost:3000. You will get a response in secure mode.

 

That’s all for now. Thank you for reading and I hope this demo will be very helpful to understanding the setup https module in nodejs express application. You can find more nodejs sample application here

Let me know your thoughts over the email demo.jsonworld@gmail.com. I would love to hear them and If you like this article, share with your friends.

 


WHAT'S NEW

Find other similar Articles here: