Working with HTTPS Server

1. Creating HTTPS Server (https.createServer)

Example

import https from "node:https";
import fs from "node:fs";
const opts = { key: fs.readFileSync("key.pem"), cert: fs.readFileSync("cert.pem") };
https.createServer(opts, app).listen(443);

2. Loading SSL Certificates

OptionPurpose
keyPrivate key (PEM)
certServer certificate
caCA bundle / chain
passphraseIf key is encrypted
pfxPKCS#12 bundle (alternative)

3. Configuring TLS Options

OptionUse
minVersion / maxVersion"TLSv1.3"
ciphersOpenSSL cipher list
requestCert / rejectUnauthorizedmTLS settings
SNICallbackMulti-domain certs
ALPNProtocolse.g. ["h2","http/1.1"]

4. Handling Secure Connections

EventFires
secureConnectionTLS handshake done
tlsClientErrorHandshake failure

5. Testing with Self-Signed Certificates

Example

openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem \
  -sha256 -days 365 -nodes -subj "/CN=localhost"
Warning: Setting NODE_TLS_REJECT_UNAUTHORIZED=0 is dev-only — never use in production.

6. Using Let's Encrypt Certificates

ToolUse
certbotManual / cron renewal
acme-client (npm)Programmatic ACME
greenlockExpress integration
caddy (reverse proxy)Auto HTTPS

7. Redirecting HTTP to HTTPS

Example

http.createServer((req, res) => {
  res.writeHead(301, { Location: `https://${req.headers.host}${req.url}` }).end();
}).listen(80);

8. Implementing Certificate Pinning

StrategyDetail
Custom checkServerIdentityValidate cert fingerprint
HPKP headerDEPRECATED in browsers
App-side pinningMobile / native clients only

9. Handling TLS Errors

Error CodeMeaning
CERT_HAS_EXPIREDRenew cert
UNABLE_TO_VERIFY_LEAF_SIGNATUREMissing intermediate CA
DEPTH_ZERO_SELF_SIGNED_CERTSelf-signed (test certs)
ERR_TLS_CERT_ALTNAME_INVALIDHostname mismatch

10. Renewing SSL Certificates

Renewal Workflow

  1. Run certbot renew on schedule (cron / systemd timer)
  2. Reload server (systemctl reload) or watch cert files via fs.watch
  3. Re-create TLS context using server.setSecureContext({ key, cert })
  4. Monitor cert expiry with alerts (e.g., 30 days warning)