Skip to content

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

ts
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; includeSubDomains
  • X-Frame-Options: SAMEORIGIN
  • Referrer-Policy: no-referrer
  • X-Content-Type-Options: nosniff
  • Cross-Origin-Opener-Policy: same-origin
  • Cross-Origin-Resource-Policy: same-origin
  • Origin-Agent-Cluster: ?1
  • X-DNS-Prefetch-Control: off
  • X-Download-Options: noopen
  • X-Permitted-Cross-Domain-Policies: none
  • X-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.

ts
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).

ts
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.