Before you can secure an application, you need to understand the ground it stands on: the encrypted connection between the browser and your server, the cookies that remember who a user is, and the rules browsers enforce to keep one website from reading another's data. This lesson explains each of them, shows the headers that control them, and points out the mistakes that quietly undo their protection.
Before you start
You should know what an HTTP request and response look like, and be comfortable running curl in a terminal and opening your browser's developer tools. Lesson 1, What Is Web Security and Privacy?, introduced confidentiality and integrity; TLS is how the web provides both in transit.
What HTTPS and TLS protect
HTTPS is plain HTTP sent inside a TLS (Transport Layer Security) connection. TLS gives you three properties between the browser and the server:
- Confidentiality: people on the network path, such as a café Wi-Fi operator or an internet provider, can't read the requests or responses.
- Integrity: they can't change the content without the change being detected. Without TLS, a network can inject ads or scripts into your page.
- Server authentication: the browser checks that the server holds a valid certificate for the domain, so it's talking to your server and not an impostor.
TLS 1.3 (RFC 8446) is the current version and should be your default; TLS 1.2 is still widely supported and acceptable when configured with modern cipher suites. Older versions (SSL, TLS 1.0, TLS 1.1) are deprecated and should be disabled.
What TLS doesn't protect
TLS protects data in transit. It does nothing once the data arrives. If your application has an SQL injection, the attacker's request travels over a perfectly encrypted connection. If your database is copied, TLS was never involved. The network path also still sees some metadata: the server's IP address and, in most connections today, the domain name in the TLS handshake.
Certificates in one minute
A TLS certificate binds a public key to one or more domain names, and is signed by a certificate authority (CA) that browsers trust. When a browser connects, the server proves it holds the matching private key. Free, automated certificates from CAs such as Let's Encrypt, renewed with the ACME protocol, have made HTTPS the default for nearly every site.
You can look at a server's certificate from the terminal:
# Show the certificate subject, issuer, and validity dates for a site you operate
openssl s_client -connect your-site.test:443 -servername your-site.test </dev/null 2>/dev/null \
| openssl x509 -noout -subject -issuer -datesTreat the private key like a password: readable only by the web server, never committed to Git, never sent to anyone.
Redirects and HSTS
Users still type bare domains, and old links still point to http://. The server should answer every plain HTTP request with a permanent redirect to HTTPS. But that first plain request is itself unprotected: a network attacker can intercept it and keep the user on HTTP.
HTTP Strict Transport Security (HSTS, RFC 6797) closes that gap. Once a browser has seen this header over HTTPS, it refuses to use plain HTTP for that domain until the time runs out:
Strict-Transport-Security: max-age=31536000; includeSubDomainsmax-ageis in seconds; one year is common. Start with a short value, such as a day, while you confirm every subdomain works over HTTPS, then raise it.includeSubDomainsapplies the rule to every subdomain. Only add it when they all support HTTPS.- Browsers ignore HSTS headers received over plain HTTP.
Browsers also ship an HSTS preload list, so a domain on it is HTTPS-only even on the first visit. Adding the preload directive and submitting the domain is a commitment that's slow to undo, so treat it as an optional step for when you're sure.
How cookies work
HTTP is stateless: each request stands alone. Cookies let a server remember something between requests. The server sends a Set-Cookie header, and the browser sends the value back on later requests to that site in a Cookie header. Session cookies, which carry a random identifier that points to a signed-in session on the server, are the most security-sensitive cookies an application sets.
Cookie attributes that matter for security
This is a good default for a session cookie:
Set-Cookie: __Host-session=6f1c9e3a2b...; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age=28800Each part has a job:
Secure: the browser sends the cookie only over HTTPS, so it never crosses the network in clear text.HttpOnly: JavaScript on the page can't read it throughdocument.cookie. If an attacker manages to run a script on your page (cross-site scripting, lesson 8), they still can't simply copy the session identifier.SameSite: controls whether the cookie is sent on requests that come from other sites.Laxsends it on top-level navigations such as following a link, but not on cross-site form posts, images, or fetches.Strictnever sends it cross-site, which is safest but means users following a link from elsewhere arrive signed out.Nonealways sends it and requiresSecure; use it only when you truly need cross-site cookies.__Host-prefix: browsers accept a cookie with this name only if it hasSecure,Path=/, and noDomainattribute. That stops a subdomain from setting or overwriting it.Max-AgeorExpires: without either, the cookie lasts until the browser session ends (and browsers that restore sessions may keep it longer). Pick a lifetime that fits the application; lesson 9 covers session expiry on the server.
Modern browsers treat cookies without a SameSite attribute as Lax by default, but behavior varies between browsers and over time, so always set it explicitly.
Setting it from code
In an Express application, the equivalent looks like this:
import { randomBytes } from "node:crypto";
import type { Response } from "express";
export function issueSessionCookie(res: Response, sessionId: string) {
res.cookie("__Host-session", sessionId, {
httpOnly: true,
secure: true,
sameSite: "lax",
path: "/",
maxAge: 8 * 60 * 60 * 1000, // milliseconds in Express
});
}
// Session identifiers must be unguessable: at least 128 bits from a CSPRNG.
export const newSessionId = () => randomBytes(32).toString("base64url");Never put personal data, roles, or anything you'd trust in a plain cookie value. The user can read and change it. Store a random identifier and keep the data on the server.
The same-origin policy
An origin is the combination of scheme, host, and port. https://shop.test and https://shop.test:8443 are different origins, and so are http://shop.test and https://shop.test. The browser's same-origin policy lets a page freely read responses only from its own origin. A script on an attacker's page can make your browser send a request to your bank, but it can't read the answer.
Two consequences matter for developers:
- CORS (Cross-Origin Resource Sharing) is how a server *relaxes* the same-origin policy for specific origins. It's an opt-in to sharing, not a security feature you add. A response with
Access-Control-Allow-Origin: *lets any site read it, and reflecting whateverOriginthe request sends while also allowing credentials effectively disables the protection. - The same-origin policy stops reading, not sending. Cross-site requests that change data still need protection from CSRF, which lesson 8 covers.
SameSitecookies are a large part of that defense.
Common mistakes and troubleshooting
- Mixed content. An HTTPS page that loads scripts or images over HTTP. Browsers block active mixed content; fix the URLs rather than weakening the page.
- Expired certificates. Automate renewal and monitor the expiry date; an expired certificate takes the site down for every visitor.
- HSTS too early. A long
max-agewithincludeSubDomainsbefore every subdomain supports HTTPS makes those subdomains unreachable. Start short. - Session cookie without
HttpOnlyorSecure. Check your framework's defaults; several don't set both. - Cookie scoped too widely. Setting
Domain=.company.testshares the cookie with every subdomain, including ones run by other teams or vendors. Prefer__Host-cookies. - **"CORS error" fixed with
*.** Find out which origin actually needs access and allow only that one.
When a cookie doesn't seem to be set, open the browser's developer tools, select the request in the Network panel, and look at the response cookies. Browsers explain why they rejected a cookie, for example a SameSite=None cookie without Secure.
Practical exercise: inspect your own site
On a site you own or operate:
- Run
curl -sI http://your-domain/and confirm a single permanent redirect to HTTPS. - Run
curl -sI https://your-domain/and look forStrict-Transport-Security. - Sign in, open developer tools, and in the Application or Storage panel inspect each cookie's
Secure,HttpOnly, andSameSitevalues. - Check the certificate's expiry date with the
opensslcommand above. - In the Console, run
document.cookiewhile signed in. Your session cookie shouldn't appear.
Write down every difference from the defaults in this lesson and decide whether each one is deliberate.
Key takeaways
- TLS protects data in transit: confidentiality, integrity, and server authentication. It doesn't fix application bugs.
- Redirect HTTP to HTTPS and send HSTS, starting with a short
max-age. - Session cookies should be
Secure,HttpOnly,SameSite=LaxorStrict, ideally with the__Host-prefix, and hold only a random identifier. - The same-origin policy stops cross-origin reading; CORS relaxes it, so configure CORS narrowly.
References
- RFC 8446: The Transport Layer Security (TLS) Protocol Version 1.3 (opens in a new tab)
- RFC 6797: HTTP Strict Transport Security (opens in a new tab)
- MDN: Using HTTP cookies (opens in a new tab)
- MDN: Same-origin policy (opens in a new tab)
- MDN: Strict-Transport-Security (opens in a new tab)
- OWASP Transport Layer Security Cheat Sheet (opens in a new tab)
What's next
With the connection and the session cookie protected, the next question is how users prove who they are. Passwords, Passkeys, and Multi-Factor Authentication Explained covers current password rules, safe storage, and phishing-resistant sign-in.

