How to run node js server on https using self-signed certificate?

By Hardik Savani | April 21, 2021 | Category : Node JS


I am going to show you example of run node app on https. i explained simply step by step run node js server on https. I’m going to show you about node js https self-signed certificate. We will look at example of node js https express.

we almost run node js project using http as like bellow simple example:

const http = require('http');

const app = http.createServer(function (req, res) {

res.writeHead(200);

res.write('web-microphone-websocket');

res.end();

});

app.listen(3000, 'localhost', () => {

console.log('Socket server listening on: 3000');

});

but if you need to run this example with https link in localhost, then how you can do this. few days ago i had same issue and i must need to run node server with https because of socket io. so i found out solution how to resolve it.

let's see bellow solution:

Solution:

Generate a self-signed certificate

openssl genrsa -out key.pem

openssl req -new -key key.pem -out csr.pem

openssl x509 -req -days 9999 -in csr.pem -signkey key.pem -out cert.pem

rm csr.pem

Update server.js File:

const https = require('https');

const fs = require('fs');

const options = {

key: fs.readFileSync('key.pem'),

cert: fs.readFileSync('cert.pem')

};

const app = https.createServer(options, function (req, res) {

res.writeHead(200);

res.write('web-microphone-websocket');

res.end();

});

app.listen(3000, 'localhost', () => {

console.log('Socket server listening on: 3000');

});

now you can run node file with following command:

node server.js

it will works with https:

https://localhost:3000

i hope it can help you...



Tags : Node JS


Hardik Savani
My name is Hardik Savani. I'm a full-stack developer, entrepreneur and owner of Aatman Infotech. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.
Follow Me: Github Twitter
***Do you want me hire for your Project Work? Then Contact US.

We are Recommending you: