Skip to content

Instantly share code, notes, and snippets.

@pajaydev
Created February 3, 2021 04:19
Show Gist options
  • Save pajaydev/d64ca7a49dd1d16c1e78687c1d7314d4 to your computer and use it in GitHub Desktop.
Save pajaydev/d64ca7a49dd1d16c1e78687c1d7314d4 to your computer and use it in GitHub Desktop.
Use HTTPS for local development using node/express js

Using HTTPS for local development using node/express js

Installation:

  1. Install brew (package manager for mac os)
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"
  1. Install mkcert[https://github.com/FiloSottile/mkcert] a. For mac
brew install mkcert

b. For windows Follow this instructions to install the mkcert.

  1. Generate trusted cerificate locally
$ mkcert -install
Created a new local CA

$ mkcert [domain name]
# In our case, we will use localhost
$ mkcert localhost

Above step will create couple of files [domainname]-key.pem, [domainname].pem.

  1. Create an node app and create server js file.
npm init 
touch server.js
  1. Install express js
npm install express
  1. Copy these files created in step 3 [domainname]-key.pem, [domainname].pem and paste it in this folder.
  2. Include this below code in server.js
'use strict';

const https = require('https');
const express = require('express');
const fs = require('fs');

const options = {
    key: fs.readFileSync('[domainname]-key.pem'),
    cert: fs.readFileSync('[domainname].pem'),
  };

const app = express();
app.get('/', (req, res, next) => {
    res.send("Localhost hosted in https !")
});
https.createServer(options, app).listen(3000);
  1. Test the application by opening the browser and hitting the URL
https://localhost:3000/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment