stackademic

The leading education platform for anyone with an interest in software development.

HTTPS & TLS

Why encrypted connections matter and how to enforce them

Overview

HTTPS is HTTP layered over TLS, which encrypts traffic between the browser and server so nobody on the network can read or tamper with it. Without it, passwords, cookies, and personal data travel in plaintext and can be intercepted. TLS also verifies the server's identity through certificates, protecting users from impersonation.

Syntax / Usage

Serve everything over HTTPS and redirect HTTP to HTTPS. Then tell browsers to always use HTTPS with an HSTS header.

GET / HTTP/1.1
Host: example.com

HTTP/1.1 301 Moved Permanently
Location: https://example.com/
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload

Examples

Redirect insecure requests to HTTPS at the application layer:

app.use((req, res, next) => {
  if (req.headers["x-forwarded-proto"] !== "https") {
    return res.redirect(301, "https://" + req.headers.host + req.url);
  }
  next();
});

Mark cookies as secure so they are never sent over plain HTTP:

res.cookie("session", token, { httpOnly: true, secure: true, sameSite: "lax" });

Common Mistakes

  • Serving login or payment pages over plain HTTP
  • Redirecting to HTTPS but forgetting the HSTS header
  • Using self-signed or expired certificates in production
  • Loading mixed content (HTTP assets) on an HTTPS page
  • Leaving cookies without the secure flag so they leak over HTTP

See Also

web-security-fundamentals web-security-authentication web-security-owasp-top-ten