Security
Security headers
Response headers that make browsers refuse risky behaviour.
A browser trusts a page to do a lot: run scripts, embed other sites, guess file types. Security headers are instructions from your server that tell the browser to be stricter, which blocks whole families of attacks (clickjacking, script injection, content sniffing) even if your code has a bug. In NestJS this is helmet.
app.http(adapter) {
useSecurityHeaders {
contentSecurityPolicy = "default-src 'self'" // off (null) by default: set it for your pages
hsts = true // Strict-Transport-Security, on by default
frameOptions = "SAMEORIGIN" // clickjacking protection, the default
referrerPolicy = "no-referrer" // the default
}
}| Header | Protects against |
|---|---|
X-Content-Type-Options: nosniff | the browser guessing a file's type (a text file run as a script) |
Strict-Transport-Security (HSTS) | downgrading to plain HTTP: after the first visit the browser only uses HTTPS |
X-Frame-Options: SAMEORIGIN | clickjacking: another site showing yours in an invisible frame |
Referrer-Policy: no-referrer | leaking your URLs (with ids or tokens) to other sites |
Content-Security-Policy | script injection (XSS): the browser only runs scripts from places you list |
Cross-Origin-Opener-Policy, Cross-Origin-Resource-Policy (same-origin) | other sites reading your windows and resources |
Always sent: X-Content-Type-Options, X-DNS-Prefetch-Control, X-Download-Options, X-Permitted-Cross-Domain-Policies, and the two cross-origin policies. HSTS is on by default; turn hsts off only when the application is not served over HTTPS (local development), because a browser that has seen HSTS will refuse plain HTTP for months.
Which do I need?
- An API that returns only JSON: the defaults are enough.
- Server-rendered pages (Views): add a content security policy that lists where scripts, styles, images come from:
contentSecurityPolicy = "default-src 'self'; script-src 'self' https://cdn.example.com; img-src 'self' data:; frame-ancestors 'none'"Start strict and loosen only what breaks (the browser console reports violations). Avoid 'unsafe-inline' for scripts.
- Front end elsewhere (Next.js on another origin): the page's own server (Next.js) sets the page's headers; Kest's headers apply to its own responses.
Test it
curl -I https://your-host/ and look at the headers, or use an online scanner. In tests assert the headers on a response with TestServer.