Skip to content

Instantly share code, notes, and snippets.

@rokobuljan
Created October 31, 2024 22:08
Show Gist options
  • Save rokobuljan/728e86b626857ddc956fd46bac321ab6 to your computer and use it in GitHub Desktop.
Save rokobuljan/728e86b626857ddc956fd46bac321ab6 to your computer and use it in GitHub Desktop.
HTTPS for localhost development with local SSL certificates (Windows)
# Your HTTPS domain name i.e: local.dev
DOMAIN_NAME=
# Your server port i.e: 3000
PORT=
# Path to your local.dev+2-key.pem i.e: C:\\Users\\YOUR_USER_NAME\\local.dev+2-key.pem
SSL_KEY_PATH=
# Path to your local.dev+2.pem i.e: C:\\Users\\YOUR_USER_NAME\\local.dev+2.pem
SSL_CERT_PATH=

Setup HTTPS for localhost development on Windows

Open PowerShell as administrator

Install Chocolatey

Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))

Install mkcert

choco install mkcert

Still from PowerShell, create certificates for i.e: local.dev domain name

mkcert local.dev 127.0.0.1 ::1

you should get this output in terminal:

Created a new certificate valid for the following names πŸ“œ
 - "local.dev"
 - "127.0.0.1"
 - "::1"

The certificate is at "./local.dev+2.pem" and the key at "./local.dev+2-key.pem" βœ…

It will expire on 31 January 2027 πŸ—“

PS: ls to find the two generated CA certificate files in that current directory. Usually in: C:\Users\YOUR_USER_NAME\

Add the following to C:\Windows\System32\drivers\etc\hosts using i.e: notepad (Run as administrator)

# Local development (HTTPS, SSL mkcert)
127.0.0.1       local.dev
::1             local.dev

NodeJS Express server

  • Run from your project directory run:

    npm init -y     # if not already initialized
    npm i express   # Install Express server
  • open package.json, add: "type": "module" and also add under "scripts": { the following:

     "dev": "node --env-file=.env --watch index.js"
  • Copy the minimal server configuration index.js (provided below) to your project root directory.

  • Do the same with the .env file (provided below), and add the needed environment values.

  • Run

    npm run dev
  • Open in browser: https://local.dev (← notice the HTTPS protocol!).
    You should finally see a "Hello, HTTPS!" message.


Additional resources

import fs from "node:fs";
import https from "node:https";
import express from "express";
const app = express();
const options = {
key: fs.readFileSync(process.env.SSL_KEY_PATH),
cert: fs.readFileSync(process.env.SSL_CERT_PATH),
};
app.get("/", (req, res) => {
res.send("Hello, HTTPS!");
});
https.createServer(options, app).listen(process.env.PORT, () => {
console.log(`Server running at https://${process.env.DOMAIN_NAME}:${process.env.PORT}`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment