Overview
Set security headers for production with environment-aware configuration.
Features
- Content Security Policy
- HSTS configuration
- XSS protection
- Production/development modes
Installation
npx hanma add hono-security --framework hono
Dependencies
hono
Code
import { secureHeaders } from "hono/secure-headers";
import { Hono } from "hono";
/**
* Production security headers configuration
*/
export const productionSecurity = secureHeaders({
contentSecurityPolicy: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", "https://trusted.cdn.com"],
styleSrc: ["'self'", "'unsafe-inline'"],
imgSrc: ["'self'", "data:", "https:"],
connectSrc: ["'self'", "https://api.trusted.com"],
fontSrc: ["'self'"],
objectSrc: ["'none'"],
mediaSrc: ["'self'"],
frameSrc: ["'none'"],
baseUri: ["'self'"],
formAction: ["'self'"],
frameAncestors: ["'none'"],
upgradeInsecureRequests: [],
},
strictTransportSecurity: "max-age=31536000; includeSubDomains; preload",
xFrameOptions: "DENY",
xContentTypeOptions: "nosniff",
referrerPolicy: "strict-origin-when-cross-origin",
xXssProtection: "1; mode=block",
});
/**
* Development security headers (relaxed)
*/
export const developmentSecurity = secureHeaders({
contentSecurityPolicy: false,
});
/**
* Setup security headers based on environment
*/
export const setupSecurity = (app: Hono) => {
const isProd = process.env.NODE_ENV === "production";
app.use("*", isProd ? productionSecurity : developmentSecurity);
};
Usage
import { setupSecurity } from './middleware/security';
setupSecurity(app);
Dependencies
hono
Frequently Asked Questions
How do I install Security Headers?
Run the following command:
npx hanma add hono-security --framework honoWhat dependencies are required?
This snippet requires: hono. 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/security.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.