JAVASCRIPT
Enforcing HTTP Security Headers with Helmet in Node.js Express
Strengthen your web application's security by easily configuring essential HTTP security headers like HSTS, X-Frame-Options, and X-Content-Type-Options using the `helmet` middleware in Node.js Express.
const express = require('express');
const helmet = require('helmet'); // Helmet helps set various security headers
const app = express();
const port = 3000;
// Use Helmet middleware to set a collection of security-related HTTP headers
app.use(helmet());
// Customize individual headers if needed (Helmet default options are generally good)
// HSTS (Strict-Transport-Security)
app.use(helmet.hsts({
maxAge: 31536000, // 1 year in seconds
includeSubDomains: true, // Apply to subdomains too
preload: true // Optionally add to browser's HSTS preload list (requires submission)
}));
// X-Frame-Options to prevent clickjacking
app.use(helmet.frameguard({ action: 'deny' })); // 'deny' or 'sameorigin'
// X-Content-Type-Options to prevent MIME-sniffing attacks
app.use(helmet.noSniff());
// X-XSS-Protection (often superseded by CSP, but still useful for older browsers)
app.use(helmet.xssFilter());
// Referrer-Policy
app.use(helmet.referrerPolicy({ policy: 'same-origin' }));
// Example route
app.get('/', (req, res) => {
res.send(`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Security Headers Demo</title>
</head>
<body>
<h1>HTTP Security Headers Enabled!</h1>
<p>Inspect your browser's network tab to see the security headers in action.</p>
<p>This includes: Strict-Transport-Security, X-Frame-Options, X-Content-Type-Options, X-XSS-Protection, Referrer-Policy.</p>
</body>
</html>
`);
});
app.listen(port, () => {
console.log(`Server running with enhanced security headers at http://localhost:${port}`);
});
How it works: This Node.js Express snippet demonstrates how to easily implement crucial HTTP security headers using the `helmet` middleware. These headers significantly harden your web application against common attacks. `Strict-Transport-Security` (HSTS) forces clients to use HTTPS, preventing downgrade attacks. `X-Frame-Options` (set to 'deny') stops clickjacking by disallowing your site from being embedded in iframes. `X-Content-Type-Options` (set to 'nosniff') prevents browsers from MIME-sniffing content types, mitigating certain XSS risks. `X-XSS-Protection` activates built-in XSS filters in older browsers, and `Referrer-Policy` controls how much referrer information is sent with requests, enhancing privacy.