Overview
Add comprehensive security headers using @fastify/helmet. Includes CSP, HSTS, and XSS protection.
Features
- Content Security Policy
- HSTS with preload
- XSS protection
- Environment-aware configs
- API-specific preset
Installation
npx hanma add fastify-helmet --framework fastify
Dependencies
fastify, @fastify/helmet
Code
import { FastifyInstance } from "fastify";
import helmet, { FastifyHelmetOptions } from "@fastify/helmet";
/**
* Default Helmet configuration for production
*/
export const productionHelmetOptions: FastifyHelmetOptions = {
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
styleSrc: ["'self'", "'unsafe-inline'"],
scriptSrc: ["'self'"],
imgSrc: ["'self'", "data:", "https:"],
connectSrc: ["'self'"],
fontSrc: ["'self'"],
objectSrc: ["'none'"],
mediaSrc: ["'self'"],
frameSrc: ["'none'"],
},
},
crossOriginEmbedderPolicy: true,
crossOriginOpenerPolicy: { policy: "same-origin" },
crossOriginResourcePolicy: { policy: "same-origin" },
dnsPrefetchControl: { allow: false },
frameguard: { action: "deny" },
hidePoweredBy: true,
hsts: {
maxAge: 31536000, // 1 year
includeSubDomains: true,
preload: true,
},
ieNoOpen: true,
noSniff: true,
originAgentCluster: true,
permittedCrossDomainPolicies: { permittedPolicies: "none" },
referrerPolicy: { policy: "strict-origin-when-cross-origin" },
xssFilter: true,
};
/**
* Development Helmet configuration - relaxed for ease of development
*/
export const developmentHelmetOptions: FastifyHelmetOptions = {
contentSecurityPolicy: false, // Disabled for hot reload and devtools
crossOriginEmbedderPolicy: false,
crossOriginOpenerPolicy: false,
crossOriginResourcePolicy: false,
hsts: false,
};
/**
* API-only Helmet configuration - no CSP since no HTML is served
*/
export const apiHelmetOptions: FastifyHelmetOptions = {
contentSecurityPolicy: false,
crossOriginEmbedderPolicy: true,
crossOriginOpenerPolicy: { policy: "same-origin" },
crossOriginResourcePolicy: { policy: "cross-origin" }, // Allow API access
dnsPrefetchControl: { allow: false },
frameguard: { action: "deny" },
hidePoweredBy: true,
hsts: {
maxAge: 31536000,
includeSubDomains: true,
},
noSniff: true,
referrerPolicy: { policy: "strict-origin-when-cross-origin" },
xssFilter: true,
};
/**
* Register Helmet middleware with environment-aware defaults
*/
export async function registerHelmet(
app: FastifyInstance,
options?: FastifyHelmetOptions
): Promise<void> {
const isDev = process.env.NODE_ENV === "development";
const isApi = process.env.APP_TYPE === "api";
let helmetOptions: FastifyHelmetOptions;
if (options) {
helmetOptions = options;
} else if (isDev) {
helmetOptions = developmentHelmetOptions;
app.log.info("[Helmet] Using development configuration (relaxed)");
} else if (isApi) {
helmetOptions = apiHelmetOptions;
app.log.info("[Helmet] Using API configuration");
} else {
helmetOptions = productionHelmetOptions;
app.log.info("[Helmet] Using production configuration");
}
await app.register(helmet, helmetOptions);
}
// Usage:
// await registerHelmet(app);
// Or with custom options:
// await registerHelmet(app, { contentSecurityPolicy: false });
Usage
import { registerHelmet } from './middleware/helmet';
await registerHelmet(app);
Dependencies
fastify@fastify/helmet
Frequently Asked Questions
How do I install Helmet Security?
Run the following command:
npx hanma add fastify-helmet --framework fastifyWhat dependencies are required?
This snippet requires: fastify, @fastify/helmet. Make sure to install them before using the snippet.
How do I use this snippet?
Copy the code and paste it into your project. The snippet will be saved to
src/middleware/helmet.ts.Can I customize this snippet?
Yes! All snippets are copy-paste code that you own. Feel free to modify them to fit your needs.
Does this work with other frameworks?
This snippet is designed for the specific framework. Check the other framework pages for equivalent implementations.