Security Headers
@modularityjs/http-fastify-security-headers is a thin wrapper around @fastify/helmet that sets the canonical security response headers (CSP, HSTS, X-Frame-Options, Referrer-Policy, etc.). Defaults follow helmet — strict policies that work for most apps and can be overridden per directive.
Setup
import { HttpModule } from '@modularityjs/http';
import { HttpFastifyModule } from '@modularityjs/http-fastify';
import { HttpFastifySecurityHeadersModule } from '@modularityjs/http-fastify-security-headers';
const modules = [
HttpModule.forRoot({ port: 3000 }),
HttpFastifyModule,
HttpFastifySecurityHeadersModule, // defaults work for most apps
];Plain HttpFastifySecurityHeadersModule (no forRoot) sends helmet's strict defaults:
Content-Security-Policy: default-src 'self';base-uri 'self'; …(very strict — blocks inline scripts and external CDNs)Strict-Transport-Security: max-age=15552000; includeSubDomainsX-Frame-Options: SAMEORIGINReferrer-Policy: no-referrerX-Content-Type-Options: nosniffCross-Origin-Opener-Policy: same-originCross-Origin-Resource-Policy: same-originOrigin-Agent-Cluster: ?1X-DNS-Prefetch-Control: offX-Download-Options: noopenX-Permitted-Cross-Domain-Policies: noneX-XSS-Protection: 0
Overriding individual headers
Each directive accepts true (helmet default), false (disable header), or an options object that helmet merges into its policy.
HttpFastifySecurityHeadersModule.forRoot({
contentSecurityPolicy: {
directives: {
'default-src': ["'self'"],
'script-src': ["'self'", 'https://cdn.example.com'],
'style-src': ["'self'", "'unsafe-inline'"],
'img-src': ["'self'", 'data:', 'https://cdn.example.com'],
},
},
hsts: { maxAge: 63072000, includeSubDomains: true, preload: true }, // 2 years
frameguard: { action: 'deny' },
crossOriginEmbedderPolicy: { policy: 'require-corp' },
});Disabling specific headers
Pass false for any header that the app emits itself or that doesn't apply (e.g. APIs that don't render HTML don't need a CSP).
HttpFastifySecurityHeadersModule.forRoot({
contentSecurityPolicy: false, // API does not render HTML
hsts: false, // a reverse proxy already adds it
});Ordering note
Internally the module registers @fastify/helmet during afterLoad, before HttpFastifyModule registers controller routes in onInit. This ordering is required so helmet's onSend hooks attach to all subsequent routes.