ItSolutionStuff.com

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

By Hardik Savani • May 1, 2024
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

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

šŸ“ŗ Subscribe on YouTube

We Are Recommending You

ā˜…

Node JS Mysql Connection Example

Read Now →
ā˜…

Node JS Multer Rename Uploaded File Example

Read Now →
ā˜…

Node JS Convert Image File to Base64 String Example

Read Now →
ā˜…

Node JS Resize Image Before Upload using Multer Sharp

Read Now →
ā˜…

Multiple File Upload in Node JS using Multer Example

Read Now →
ā˜…

Node js Express Multiple Image Upload using Multer Example

Read Now →
ā˜…

File Upload in Node JS using Multer Example

Read Now →
ā˜…

Node js Express Image Upload using Multer Example

Read Now →
ā˜…

How to Connect MySQL Database in Node JS?

Read Now →
ā˜…

Laravel Authenticate User in NodeJS with Socket io using JWT

Read Now →
ā˜…

How to Upgrade Node.js Version in Ubuntu?

Read Now →