Sensible Security Headers in One Line
@fastify/helmet
The @fastify/helmet plugin sets a bundle of HTTP security headers — CSP, HSTS, X-Frame-Options, X-Content-Type-Options, and more.
What you'll learn
- Install @fastify/helmet
- Register early at boot
- Tune the Content Security Policy for assets and CDNs
Helmet is a port of the popular Express middleware. It sets headers that prevent a long list of common attacks — clickjacking, MIME sniffing, mixed content, and more.
Install & Register
npm install @fastify/helmet import helmet from '@fastify/helmet'
await app.register(helmet, {
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
'img-src': ["'self'", 'data:', 'cdn.example.com'],
'script-src': ["'self'"],
},
},
}) Register Helmet near the top of app.ts so the headers apply to every response, including 404s and errors.
What You Get
By default Helmet sets, among others:
Strict-Transport-Security: max-age=15552000; includeSubDomainsX-Content-Type-Options: nosniffX-Frame-Options: SAMEORIGINReferrer-Policy: no-referrer- A strict default
Content-Security-Policy
Tuning CSP for Your Assets
A strict CSP often breaks third-party widgets — adjust the directives instead of disabling CSP entirely.
await app.register(helmet, {
contentSecurityPolicy: {
directives: {
'script-src': ["'self'", 'plausible.io'],
'connect-src': ["'self'", 'api.example.com'],
'frame-ancestors': ["'none'"],
},
},
}) If you must skip CSP for a single route — say a status endpoint — pass { contentSecurityPolicy: false } to a sub-plugin rather than disabling globally.