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
| Option | Purpose |
key | Private key (PEM) |
cert | Server certificate |
ca | CA bundle / chain |
passphrase | If key is encrypted |
pfx | PKCS#12 bundle (alternative) |
3. Configuring TLS Options
| Option | Use |
minVersion / maxVersion | "TLSv1.3" |
ciphers | OpenSSL cipher list |
requestCert / rejectUnauthorized | mTLS settings |
SNICallback | Multi-domain certs |
ALPNProtocols | e.g. ["h2","http/1.1"] |
4. Handling Secure Connections
| Event | Fires |
secureConnection | TLS handshake done |
tlsClientError | Handshake 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
| Tool | Use |
certbot | Manual / cron renewal |
acme-client (npm) | Programmatic ACME |
greenlock | Express 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
| Strategy | Detail |
| Custom checkServerIdentity | Validate cert fingerprint |
| HPKP header | DEPRECATED in browsers |
| App-side pinning | Mobile / native clients only |
9. Handling TLS Errors
| Error Code | Meaning |
CERT_HAS_EXPIRED | Renew cert |
UNABLE_TO_VERIFY_LEAF_SIGNATURE | Missing intermediate CA |
DEPTH_ZERO_SELF_SIGNED_CERT | Self-signed (test certs) |
ERR_TLS_CERT_ALTNAME_INVALID | Hostname mismatch |
10. Renewing SSL Certificates
Renewal Workflow
- Run
certbot renew on schedule (cron / systemd timer)
- Reload server (
systemctl reload) or watch cert files via fs.watch
- Re-create TLS context using
server.setSecureContext({ key, cert })
- Monitor cert expiry with alerts (e.g., 30 days warning)