Topic 47 of 55
Helmet.js Security Headers
Overview
Helmet helps secure your Express apps by setting various HTTP headers. It protects against common web vulnerabilities like Cross-Site Scripting (XSS), Clickjacking, and sniffing by instructing the browser on how it should behave.
Syntax
javascript
// 1. Install helmet
// npm install helmet
const express = require('express');
const helmet = require('helmet');
const app = express();
// Apply helmet at the very top of your middleware stack
app.use(helmet());
// What Helmet does under the hood:
// - Removes the 'X-Powered-By' header (so hackers don't know you use Express)
// - Sets 'X-Frame-Options' to block Clickjacking (stops others from putting your site in an iframe)
// - Sets 'Strict-Transport-Security' to enforce HTTPS
// - Sets 'X-Content-Type-Options' to prevent browsers from guessing file types
app.get('/', (req, res) => res.send('Secure API'));Common Pitfalls
- Adding Helmet to an existing legacy application might break it if the app relies on loading external scripts or being embedded in iframes. Test thoroughly.
- Helmet is not a silver bullet. It mitigates frontend vulnerabilities via headers but does nothing to prevent SQL injection or bad backend logic.
Real-World Example
Customizing the Content Security Policy (CSP) when using Helmet:
example
javascript
// Sometimes Helmet's default CSP blocks external images or scripts
// you actually want to load (like Google Fonts or Stripe JS).
app.use(
helmet.contentSecurityPolicy({
directives: {
defaultSrc: ["'self'"], // Only allow resources from your own domain
scriptSrc: ["'self'", "https://js.stripe.com"], // Allow your scripts AND Stripe
imgSrc: ["'self'", "https://images.unsplash.com", "data:"],
styleSrc: ["'self'", "https://fonts.googleapis.com", "'unsafe-inline'"],
},
})
);