HTTPS in Node.js: Secure Servers and Encrypted Requests

The node:https module implements the HTTP protocol over TLS/SSL in Node.js. . It enables developers to create secure servers, manage encrypted connections, and send HTTPS requests. By using TLS certificates, developers can establish secure communication channels, leverage agents for connection management, and ensure client requests are transmitted securely.

https.Agent / https.globalAgenthttps.Server / https.createServerhttps.request / https.getTLS certificates / session resumptionkeylog event / certificate pinning

~2 min read • Updated Dec 29, 2025

1. Introduction


HTTPS is the secure version of HTTP, using TLS/SSL for encrypted communication. In Node.js, it is implemented as a separate module.


2. Class: https.Agent


  • Similar to http.Agent but for TLS connections.
  • Options include maxCachedSessions for TLS session caching and servername for SNI.
  • Event: keylog: Emits TLS key material for debugging and traffic decryption (e.g., with Wireshark).

3. Class: https.Server


  • Extends tls.Server.
  • Key methods: close(), setTimeout(), closeAllConnections(), closeIdleConnections().
  • Properties: headersTimeout, requestTimeout, keepAliveTimeout.

4. Creating an HTTPS Server


const https = require('node:https');
const fs = require('node:fs');

const options = {
  key: fs.readFileSync('private-key.pem'),
  cert: fs.readFileSync('certificate.pem'),
};

https.createServer(options, (req, res) => {
  res.writeHead(200);
  res.end('hello world\\n');
}).listen(8000);

Certificates can be generated using openssl for testing purposes.


5. Method: https.get()


  • Similar to http.get() but for secure requests.
  • Defaults to GET and automatically calls req.end().

6. Method: https.request()


  • Allows sending secure requests with full control.
  • Options include ca, cert, key, pfx, rejectUnauthorized.
  • Supports custom agents or disabling agents for direct connections.

7. Certificate Pinning


Using checkServerIdentity and SHA256 hashes, developers can pin certificates or public keys to enhance security.


8. Example: HTTPS Request


const https = require('node:https');

https.get('https://encrypted.google.com/', (res) => {
  console.log('statusCode:', res.statusCode);
  console.log('headers:', res.headers);

  res.on('data', (d) => process.stdout.write(d));
}).on('error', (e) => {
  console.error(e);
});

Conclusion


The https module in Node.js provides robust tools for building secure servers and sending encrypted requests. With TLS certificates, agent management, and features like certificate pinning, developers can ensure secure and reliable communication.


Written & researched by Dr. Shahin Siami