Course contentsShow
← Node.js
Lesson 566 of 1,9806. Networking and HTTP FundamentalsFree lesson

TLS/SSL Handshake Basics

Configure TLS certificates to wrap standard HTTP traffic in a secure encrypted layer.

In this lesson, you will learn how to wrap standard HTTP traffic in a secure encrypted layer by configuring TLS certificates for your Node.js server.

Why Encrypt HTTP?

Standard HTTP sends data as "plaintext," meaning anyone intercepting the network traffic can read your users' messages or credentials. TLS (Transport Layer Security) wraps that traffic in an encrypted tunnel. Before data is sent, the client and server perform a "handshake" to negotiate security settings and verify each other's identity using certificates.

Configuring TLS in Node.js

To secure your server, you need a digital certificate (the public identity) and a private key (the secret used for decryption). Node.js provides the https module to handle this process. Instead of creating a plain http server, you provide your security credentials to an https server instance.

Here is a simplified look at how you wrap your existing logic in a secure layer:

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

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

// Instead of http.createServer, we use https.createServer
https.createServer(options, (req, res) => {
  res.writeHead(200);
  res.end('This traffic is now encrypted via TLS!');
}).listen(443);

The Handshake Process

When a client connects to your server on port 443, the following happens behind the scenes:

  1. ClientHello: The browser says, "Hello! I support these encryption methods."
  2. ServerHello: Your server responds, "Let's use this specific method, and here is my certificate to prove I am who I say I am."
  3. Key Exchange: The client and server agree on a temporary "session key."
  4. Encrypted Tunnel: Both sides switch to using this session key to encrypt everything that follows.

By using https.createServer, you ensure that the entire communication layer is shielded from eavesdropping, fulfilling the handshake requirement before your application logic even receives the request.

Key Takeaway: TLS provides a secure wrapper for HTTP by using a certificate-based handshake to establish an encrypted tunnel between the client and your server before any application data is exchanged.