JAVASCRIPT
Implement Essential Security Headers with Helmet.js
Enhance your Express.js application's security by automatically setting various HTTP security headers using the Helmet.js middleware to mitigate common web vulnerabilities.
const express = require('express');
const helmet = require('helmet'); // Import Helmet middleware
const app = express();
// Use Helmet to set various HTTP headers for security
app.use(helmet());
// You can configure individual Helmet middleware components as needed:
// HSTS (Strict-Transport-Security)
// app.use(helmet.hsts({
// maxAge: 31536000, // 1 year in seconds
// includeSubDomains: true,
// preload: true
// }));
// CSP (Content-Security-Policy) - Example, configure carefully!
// app.use(helmet.contentSecurityPolicy({
// directives: {
// defaultSrc: ["'self'"],
// scriptSrc: ["'self'", "'unsafe-inline'"], // Generally avoid 'unsafe-inline'
// styleSrc: ["'self'", "https://fonts.googleapis.com"],
// imgSrc: ["'self'", "data:"],
// connectSrc: ["'self'"],
// fontSrc: ["'self'", "https://fonts.gstatic.com"],
// objectSrc: ["'none'"],
// mediaSrc: ["'self'"],
// frameSrc: ["'none'"]
// }
// }));
// X-Frame-Options (Clickjacking protection) - Default is SAMEORIGIN
// app.use(helmet.frameguard({ action: 'deny' })); // Or 'sameorigin'
// X-Content-Type-Options (MIME-type sniffing protection) - Default is nosniff
// app.use(helmet.noSniff());
// X-DNS-Prefetch-Control - Default is off
// app.use(helmet.dnsPrefetchControl({ allow: true }));
// X-Permitted-Cross-Domain-Policies - Default is none
// app.use(helmet.permittedCrossDomainPolicies());
// Referrer-Policy - Default is no-referrer
// app.use(helmet.referrerPolicy({ policy: 'no-referrer' }));
// Simple route
app.get('/', (req, res) => {
res.send('<h1>Hello, secure web!</h1><p>Check your browser\'s network tab for security headers.</p>');
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
// To verify:
// Start the server, then open http://localhost:3000 in your browser.
// Open Developer Tools (F12), go to Network tab, refresh the page, click on the request.
// Look at the "Response Headers" section. You should see headers like:
// X-DNS-Prefetch-Control, X-Frame-Options, Strict-Transport-Security (if enabled),
// X-Download-Options, X-Content-Type-Options, X-XSS-Protection etc.
How it works: This Node.js snippet demonstrates how to easily implement a suite of essential HTTP security headers in an Express.js application using the `helmet` middleware. By simply calling `app.use(helmet())`, it automatically sets headers like `X-Content-Type-Options` (to prevent MIME-type sniffing), `X-Frame-Options` (to mitigate clickjacking), `X-XSS-Protection`, and more, providing a robust first line of defense against common web vulnerabilities. Individual headers can also be configured with more granular control if needed.