helmet
Headers
1. The Theory: Why Headers Matter?
Theory: By default, Express reveals a lot of information in its response headers that hackers can use to plan an attack
Information Leakage: For example, the
X-Powered-By: Expressheader tells an attacker exactly what technology you are using, allowing them to target specific Node.js or Express vulnerabilities .Browser Behavior: Modern browsers have built-in security features (like blocking unauthorized scripts), but they only activate these features if the server tells them to via specific headers
.
2. What Helmet Does (Key Protections)
Theory: Helmet is a collection of 15 smaller middleware functions, each setting a specific security-related header
contentSecurityPolicy(CSP): Prevents Cross-Site Scripting (XSS) and data injection by restricting where resources (scripts, images) can be loaded from. dnsPrefetchControl: Disables DNS prefetching, which protects user privacy by preventing browsers from looking up IP addresses before a link is clicked. frameguard: Prevents Clickjacking by stopping your site from being embedded in an<iframe>on another site. hidePoweredBy: Removes theX-Powered-Byheader so attackers don't know you're using Express. hsts(Strict-Transport-Security): Forces the browser to only communicate with your server over HTTPS.
3. Implementation in Express
Theory: Helmet should be one of the very first middlewares you call in your app.js file to ensure all subsequent responses are protected
const express = require('express');
const helmet = require('helmet');
const app = express();
// Use helmet early in the middleware stack
app.use(helmet());
app.get('/', (req, res) => {
res.send('Secure site!');
});4. Customizing Content Security Policy (CSP)
Theory: Sometimes the default Helmet settings are too strict (e.g., they might block your React app from loading Google Fonts)
app.use(
helmet.contentSecurityPolicy({
directives: {
"default-src": ["'self'"], // Only load resources from your own domain
"script-src": ["'self'", "trusted-scripts.com"], // Allow scripts from specific sites
"style-src": ["'self'", "fonts.googleapis.com"] // Allow Google Fonts
},
})
);.