Appearance
TLS and Security Headers
17. What is HTTPS, and how does TLS protect data in transit?
The short answer
HTTPS is plain HTTP sent inside a TLS connection. TLS gives three protections. Confidentiality: everything is encrypted, so someone on the café Wi-Fi sees only scrambled bytes. Integrity: every record carries a check value, so any change in transit is detected. Authentication: the server proves it really is shop.example with a certificate signed by a certificate authority the browser trusts. The handshake uses public-key cryptography to agree on fresh shared keys, then fast symmetric encryption carries the data.
Two kinds of encryption, and why TLS uses both. Symmetric encryption, such as AES, uses one shared key to lock and unlock. It is very fast, but both sides need the same key first. Asymmetric, or public-key, cryptography uses a key pair: anyone can use the public key, only the owner holds the private key. It is slow, but it lets two strangers agree on a secret over an open network. TLS uses the slow kind once, in the handshake, to agree on a key, then the fast kind for all the data.
What the certificate proves, step by step:
- The server sends its certificate: its name and public key, signed by an intermediate certificate authority.
- The browser follows the chain up to a root authority already stored in the operating system or browser.
- It checks the name on the certificate matches the address bar, and that the dates are valid.
- The server signs part of the handshake with its private key. Only the real owner of the certificate can do that, so a copied certificate is useless to an impostor.
Forward secrecy. The key shares are fresh for every connection and thrown away afterwards. If the server's private key leaks next year, recorded traffic from today still cannot be decrypted. TLS 1.3 makes this mandatory.
What TLS does not hide: the server's IP address, the amount of data, timing, and usually the hostname in the handshake's Server Name Indication field. Once the data reaches the server, TLS is gone: protecting it at rest is a separate job.
18. What is the difference between SSL and TLS?
The short answer
SSL was the original protocol from Netscape in the 1990s. TLS is its renamed and redesigned successor, standardised by the IETF. Every SSL version, 2.0 and 3.0, is broken and disabled everywhere. TLS 1.0 and 1.1 were deprecated in 2021. Today you should allow only TLS 1.2 and TLS 1.3. People still say "SSL certificate" out of habit; the same certificate is used by TLS.
| Version | Year | Status |
|---|---|---|
| SSL 2.0, 3.0 | 1995, 1996 | Broken, never use |
| TLS 1.0, 1.1 | 1999, 2006 | Deprecated in 2021 |
| TLS 1.2 | 2008 | Fine with modern ciphers |
| TLS 1.3 | 2018 | Preferred |
What TLS 1.3 improved over 1.2:
- Faster. The handshake takes one round trip instead of two.
- Simpler and safer. Old weak options, such as RSA key exchange, CBC-mode ciphers and SHA-1, were removed. There is less to misconfigure.
- Forward secrecy always, because every key exchange uses fresh keys.
- More of the handshake is encrypted, including the server's certificate.
Where TLS ends in a typical deployment is the load balancer or reverse proxy. It decrypts, then forwards plain HTTP inside the private network, or re-encrypts if your security model requires it (question 42).
19. What security headers should an Express application set?
The short answer
The core set: Strict-Transport-Security to force HTTPS; Content-Security-Policy to limit where scripts and other resources may load from; X-Content-Type-Options: nosniff so browsers do not guess file types; frame-ancestors in CSP, or X-Frame-Options, to stop clickjacking; Referrer-Policy to limit what URLs leak to other sites; and Permissions-Policy to switch off browser features you do not use. Also remove X-Powered-By, and set Cache-Control: no-store on private responses. In Express, Helmet sets most of these in one line.
| Header | Stops | Typical value |
|---|---|---|
Strict-Transport-Security | Downgrade to HTTP | max-age=31536000; includeSubDomains |
Content-Security-Policy | XSS, data theft | default-src 'self' and more |
X-Content-Type-Options | MIME sniffing | nosniff |
X-Frame-Options | Clickjacking | DENY or SAMEORIGIN |
Referrer-Policy | URL leaks | strict-origin-when-cross-origin |
Permissions-Policy | Feature abuse | camera=(), geolocation=() |
Cache-Control | Private data in shared caches | no-store on account pages |
Where to set them. Either in Express with Helmet, or at the reverse proxy or CDN in front. Setting them at the edge covers static files too. Setting them in the app keeps them in version control beside the code. Many teams do both, but then must avoid two different values for the same header.
Which headers matter for a JSON API. A pure API returning JSON needs fewer: HSTS, nosniff, a strict CSP of default-src 'none', and Cache-Control. CSP and framing rules matter most on responses that render HTML.
20. What is Helmet, and why is it used?
The short answer
Helmet is a small Express middleware that sets a sensible group of security response headers with one call, app.use(helmet()). It exists because remembering and correctly writing about a dozen headers by hand is easy to get wrong. It does not fix code bugs like SQL injection or broken access control; it only tells the browser to apply extra protections. Its defaults are a good start, and you tune the Content Security Policy for your own app.
ts
import express from 'express'
import helmet from 'helmet'
const app = express()
app.use(helmet({ // (1)
contentSecurityPolicy: {
directives: {
'script-src': ["'self'", 'https://js.stripe.com'], // (2)
'img-src': ["'self'", 'data:', 'https://images.shop.example'],
'connect-src': ["'self'", 'https://api.stripe.com'],
},
},
}))- One middleware, mounted before your routes, so every response gets the headers.
- Extend the default CSP with the outside sources your shop really uses: Stripe's payment script, your image CDN and Stripe's API. Helmet merges these with its other default directives.
Why it is used in practice: it is a cheap, reviewed baseline. Security scanners and penetration testers check for these headers first, and Helmet answers most of those findings in one line.
21. Which headers does Helmet configure?
The short answer
Helmet 8 sets, by default: Content-Security-Policy, Cross-Origin-Opener-Policy, Cross-Origin-Resource-Policy, Origin-Agent-Cluster, Referrer-Policy: no-referrer, Strict-Transport-Security, X-Content-Type-Options: nosniff, X-DNS-Prefetch-Control: off, X-Download-Options, X-Frame-Options: SAMEORIGIN, X-Permitted-Cross-Domain-Policies: none and X-XSS-Protection: 0. It also removes X-Powered-By. Each one can be configured or turned off by name.
| Header | What it does |
|---|---|
Content-Security-Policy | Allow-list of where resources may load from (question 22) |
Cross-Origin-Opener-Policy: same-origin | Pages opened from other sites cannot reach your window object |
Cross-Origin-Resource-Policy: same-origin | Other sites cannot embed your responses |
Origin-Agent-Cluster | Asks the browser to isolate your origin in its own process |
Referrer-Policy: no-referrer | Sends no referrer at all (question 26) |
Strict-Transport-Security | HTTPS only for a year (question 24) |
X-Content-Type-Options: nosniff | No MIME guessing (question 25) |
X-DNS-Prefetch-Control: off | Stops the browser looking up linked domains early |
X-Download-Options: noopen | Old Internet Explorer: do not open downloads in your site's context |
X-Frame-Options: SAMEORIGIN | Only your own pages may frame you (question 25) |
X-Permitted-Cross-Domain-Policies: none | Blocks old Flash and PDF cross-domain policy files |
X-XSS-Protection: 0 | Turns off the old browser XSS filter, which caused bugs |
Why X-XSS-Protection: 0 and not 1? The old built-in filter in browsers could be tricked into removing good scripts from a page, which itself created leaks. Modern browsers removed it. CSP is the real protection now, so Helmet disables the old filter.
Turning one off:
ts
app.use(helmet({ crossOriginResourcePolicy: { policy: 'cross-origin' } })) // a public image CDN22. What is Content Security Policy (CSP)?
The short answer
CSP is a response header that gives the browser an allow-list of where scripts, styles, images, frames and connections may come from. If an attacker manages to inject <script> into your page, the browser refuses to run it because its source is not on the list. It is the strongest second line of defence against XSS. A strict modern policy allows scripts only with a per-request nonce or a hash, blocks inline event handlers and eval, and reports violations so you can find breakage.
A strict policy for a server-rendered page:
http
Content-Security-Policy:
default-src 'self';
script-src 'nonce-4f9a2b' 'strict-dynamic';
object-src 'none';
base-uri 'none';
frame-ancestors 'none';
report-to csp-endpointReading it line by line:
default-src 'self': anything not listed below may load only from your own origin.script-src 'nonce-…' 'strict-dynamic': only scripts carrying this request's nonce run. Scripts those trusted scripts load are also trusted. Inlineonclick=handlers are blocked.object-src 'none': no plug-ins such as Flash.base-uri 'none': an injected<base>tag cannot redirect your relative script URLs.frame-ancestors 'none': no site may put your page in a frame (question 25).report-to: send violation reports to an endpoint so you see attacks and breakage.
Rolling it out without breaking the site. Send it first as Content-Security-Policy-Report-Only. The browser reports what it would have blocked but blocks nothing. Fix the reports, then switch to the enforcing header.
What weakens a CSP: 'unsafe-inline' in script-src, which allows every inline script including injected ones; 'unsafe-eval'; and allowing a whole CDN host that also serves other people's files, since an attacker can load their own script from there.
23. What is the difference between a CSP nonce and a CSP hash?
The short answer
Both let specific inline or trusted scripts run while blocking injected ones. A nonce is a random value the server generates fresh for every response, puts in the CSP header, and adds to each of its own <script nonce="…"> tags. An attacker cannot guess it. A hash is the SHA-256 of a script's exact contents, listed in the header. The browser runs an inline script only if its hash matches. Use nonces for server-rendered pages, and hashes for static pages that cannot change per request.
| Nonce | Hash | |
|---|---|---|
| Value | Random per response | Fingerprint of the script text |
| Needs a server per request | Yes | No |
| Works on static hosting | No | Yes |
| Script can change freely | Yes | No, hash must be updated |
| Danger | Reusing or caching one nonce | None special |
A nonce in Express:
ts
import { randomBytes } from 'node:crypto'
app.use((req, res, next) => {
res.locals.cspNonce = randomBytes(16).toString('base64') // (1)
next()
})
app.use(helmet({
contentSecurityPolicy: {
directives: {
'script-src': ["'self'", (req, res) => `'nonce-${(res as Response).locals.cspNonce}'`], // (2)
},
},
}))
app.get('/checkout', (req, res) => {
res.send(`<script nonce="${res.locals.cspNonce}">startCheckout()</script>`) // (3)
})- A fresh random value per request: 16 random bytes, about 128 bits, impossible to guess.
- The header names this request's nonce. Helmet accepts a function per directive value.
- Your own script tags carry the same nonce. An injected tag does not know it, so it is blocked.
The rule that keeps nonces safe: never cache an HTML page containing a nonce in a shared cache. If the same nonce is served to everyone, it stops being secret.
A hash looks like this: script-src 'sha256-B2yPHKaXnvFWtRChIbabYmUBFZdVfKKXHbWtWidDVF8='. Change one space in the script and the hash no longer matches.
24. What is HSTS, and how does it improve transport security?
The short answer
HSTS, HTTP Strict Transport Security, is the header Strict-Transport-Security: max-age=31536000; includeSubDomains. It tells the browser: for the next year, only ever talk to this site over HTTPS. After the first visit, the browser rewrites any http:// link or typed address to https:// itself, before sending anything. This stops an attacker on the network from catching that first plain-HTTP request and stripping the user down to an unencrypted connection. Adding the site to the browsers' preload list protects even the very first visit.
The attack HSTS stops, called SSL stripping:
- You type
shop.examplein a café. The browser trieshttp://shop.examplefirst. - An attacker on the same Wi-Fi intercepts that plain request.
- The attacker talks HTTPS to the real shop, but keeps talking plain HTTP to you, reading everything, including your password.
With HSTS remembered from an earlier visit, step 1 never happens: the browser goes straight to HTTPS. The browser also refuses to let you click through a certificate warning on that site.
The parts of the header:
| Part | Meaning |
|---|---|
max-age=31536000 | Remember for one year, in seconds |
includeSubDomains | Apply to every subdomain too |
preload | Consent to being on the built-in browser list |
Roll out carefully. Start with a short max-age, such as 300 seconds. Check every subdomain works over HTTPS. Then raise it. Once preloaded, removing a domain from the list takes months, so an HTTP-only subdomain such as an old intranet tool would be unreachable.
HSTS is only honoured over HTTPS. The header sent on a plain-HTTP response is ignored, because an attacker could have added it. Redirect HTTP to HTTPS, then send HSTS on the HTTPS response.
25. What do X-Frame-Options and X-Content-Type-Options do?
The short answer
X-Frame-Options says whether other sites may show your page inside a frame. DENY forbids all framing, and SAMEORIGIN allows only your own site. It stops clickjacking, where an attacker hides your real page under a fake button (the clickjacking question). The modern replacement is CSP's frame-ancestors. X-Content-Type-Options: nosniff tells the browser to trust the Content-Type header and not guess. This stops an uploaded file labelled as an image from being run as a script or HTML.
Why MIME sniffing was dangerous. Old browsers looked at the first bytes of a file to guess its type. Suppose a user uploads avatar.png that really contains HTML and JavaScript. Without nosniff, a browser might decide it is HTML and run the script on your origin. That is stored XSS through an image upload. With nosniff, a file served as image/png is only ever treated as an image. A script must arrive with a JavaScript type, or it is refused.
| Want | Old header | Modern header |
|---|---|---|
| Never framed | X-Frame-Options: DENY | frame-ancestors 'none' |
| Only framed by you | X-Frame-Options: SAMEORIGIN | frame-ancestors 'self' |
| Framed by one partner | Not possible | frame-ancestors https://partner.example |
Send both framing headers. frame-ancestors wins in modern browsers. X-Frame-Options covers very old ones. Helmet sends both by default.
26. What are Referrer-Policy and Permissions-Policy?
The short answer
Referrer-Policy controls how much of the current URL the browser sends in the Referer header when the user follows a link or the page loads a resource. A URL such as /reset-password?token=abc leaking to an analytics site is a real bug. The common safe value is strict-origin-when-cross-origin: the full URL inside your own site, only the origin to other sites, and nothing when going from HTTPS to HTTP. Permissions-Policy switches off powerful browser features, such as the camera, microphone and location, for your page and any frames inside it.
What each Referrer-Policy sends when a user on https://shop.example/orders/42?coupon=X clicks a link to another site:
| Policy | Other site receives |
|---|---|
no-referrer | Nothing |
strict-origin-when-cross-origin | https://shop.example/ |
unsafe-url | The full URL, coupon included |
Browsers default to strict-origin-when-cross-origin today. Helmet sends the stricter no-referrer. Some partners and analytics tools need at least the origin, so pick deliberately.
Permissions-Policy in practice:
http
Permissions-Policy: camera=(), microphone=(), geolocation=(self), payment=(self "https://js.stripe.com")camera=(): empty list, so no page or frame may use the camera.geolocation=(self): only your own pages may ask for location, not embedded frames.payment=(…): your page and Stripe's frame may use the browser's payment request feature.
Why bother. If an advertising frame or an injected script tries to turn on the microphone, the browser refuses before even asking the user. It limits what any compromised third-party code on your page can do.