Creating a local https server

I'm just going to create a simple https server here to show how it works

/* index.js install express to test this */
const express = require('express');
const path = require('path');
const fs = require('fs');
const https = require('https');


const app = express();


app.get('*', (req, res) => {
    res.send({OK: true, msg: 'Hello! Thanks for checking'});
});

const server = https.createServer({
    key: fs.readFileSync(path.join(__dirname, 'localhost-key.pem')),
    cert: fs.readFileSync(path.join(__dirname, 'localhost-crt.pem'))
}, app);

server.listen(9080);

server.on('error', (e) => {
    console.log('error', e);
})

In the above file, there are 2 files that you need to focus on

  • localhost-key.pem

  • localhost-crt.pem

To generate these files you need to install mkcert which can be found here https://github.com/FiloSottile/mkcert

Once the installation is completed, you can run the following commands to generate the 2 files mentioned above.

# This will generate a local certificate authority
mkcert -install

# This will generate the files mentioned 
mkcert localhost 192.162.1.12

You can try to plug and play

Hope this helps