DEV Community

Cover image for ๐Ÿš€ Boost Your Node.js Security with Helmet.js! ๐Ÿ›ก๏ธ
sampod76
sampod76

Posted on

๐Ÿš€ Boost Your Node.js Security with Helmet.js! ๐Ÿ›ก๏ธ

Building secure web applications is more important than ever. If you're using Node.js and Express, Helmet.js is your go-to middleware to add an extra layer of security by configuring various HTTP headers.

  1. Content Security Policy (CSP): Fine-tune your scriptSrc and styleSrc to limit what external resources can be loaded, reducing XSS attacks.
  2. Cross-Origin Policies: Secure cross-origin resource and embedder policies to prevent unauthorized resource sharing.
  3. HSTS Preloading: Enforce HTTPS to all visitors by preloading HTTP Strict Transport Security.
  4. Frameguard: Prevent clickjacking attacks by controlling who can embed your site in iframes.
  5. XSS and MIME Protection: Add X-XSS-Protection and X-Content-Type-Options headers to guard against XSS attacks and MIME sniffing. ๐Ÿ’ก Pro Tip: Always audit your security headers regularly and stay up-to-date with emerging threats to ensure comprehensive protection. `import helmet from 'helmet';

const app: Application = express();

app.use(
helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", "'unsafe-inline'"],
// scriptSrc: ["'self'", "'unsafe-inline'", "example.com"],
styleSrc: ["'self'", "'unsafe-inline'"],
imgSrc: ["'self'", 'data:'],
connectSrc: ["'self'"],
fontSrc: ["'self'"],
objectSrc: ["'none'"],
mediaSrc: ["'self'"],
frameSrc: ["'self'"],
upgradeInsecureRequests: [],
},
},
crossOriginEmbedderPolicy: true,
crossOriginOpenerPolicy: { policy: 'same-origin' },
crossOriginResourcePolicy: { policy: 'same-origin' },
dnsPrefetchControl: { allow: false },
// expectCt: {
// enforce: true,
// maxAge: 86400, // 1 day in seconds
// },
frameguard: { action: 'deny' },
hsts: {
maxAge: 63072000, // 2 years in seconds
includeSubDomains: true,
preload: true,
},
hidePoweredBy: true,
ieNoOpen: true,
noSniff: true,
permittedCrossDomainPolicies: { permittedPolicies: 'none' },
referrerPolicy: { policy: 'strict-origin-when-cross-origin' },
xssFilter: true,
}),
);

Image description`

Top comments (0)