Skip to main content

Https Server for NodeJs

· 2 min read

Follow below steps to run a HTTPS server for your nodeJs app. To run your nodesJS + ExpressJs app on HTTPS, you need to first create a SSL certificate. To do so we will use openssl. Run below command on your terminal

openssl req -x509 -newkey rsa:2048 -keyout keytmp.pem -out cert.pem -days 365

Run below command on same terminal after cert.pem and keytmp.pem has been generated

openssl rsa -in keytmp.pem -out key.pem

Include your keys and certificatio to your app by moving them to appropraiate folder

Once you have all files in right place, update your server.js/index.js file for ExpressJS, as shown below

import express from 'express'; import https from 'https import fs from 'fs'
const port = process.env.PORT || 3003;
const key = fs.readFileSync('./server/key.pem') const cert = fs.readFileSync('./server/cert.pem'),
// we will pass our 'app' to 'https' server const server =https.createServer({ key: , cert: passphrase: 'Your Pass phrase' },app);
app.get('/', (req, res) => { res.send('This is an secure server') });
server.listen(port, () => { console.log('listening on 3003') });

Now if you run your app you can navigate to https://localhost:3003, your browser will throw a long message warning about validatiy of the SSL certificate, since it has been genrated locally by you and not generated by a Standard Certificate issuer. You can igmore and Click on continue to run your server on HTTPS.

~Happy Coding..