JAVASCRIPT
Essential Security Headers with Helmet.js
Configure essential HTTP security headers like HSTS, X-Frame-Options, and X-Content-Type-Options in Express.js using `helmet` to bolster your web application's defense.
const express = require('express');
const helmet = require('helmet');
const app = express();
// Use Helmet to set various security headers
// Helmet is a collection of 14 smaller middleware functions that set security-related HTTP response headers.
// By default, it enables 11 middlewares. You can disable/configure them individually.
app.use(helmet());
// Example: If you need to disable a specific header (e.g., Content-Security-Policy if you set it manually):
// app.use(helmet({ contentSecurityPolicy: false }));
// Example: Configure specific headers individually if needed:
// HSTS (HTTP Strict Transport Security) tells browsers to always use HTTPS for your domain for a specified duration.
app.use(helmet.hsts({
maxAge: 31536000, // 1 year in seconds
includeSubDomains: true, // Apply to subdomains as well
preload: true // Optionally enable preloading (requires submission to hstspreload.org)
}));
// X-Frame-Options to prevent clickjacking: 'DENY' (default), 'SAMEORIGIN', or 'ALLOW-FROM uri'
app.use(helmet.frameguard({ action: 'deny' }));
// X-Content-Type-Options to prevent MIME sniffing: 'nosniff' (default)
app.use(helmet.noSniff());
// X-DNS-Prefetch-Control to disable DNS prefetching for security reasons
app.use(helmet.dnsPrefetchControl({ allow: false }));
// Simple route for demonstration
app.get('/', (req, res) => {
res.send('Hello from a secure Express app!');
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
console.log('Check response headers in your browser dev tools (Network tab) for security headers.');
});
How it works: This snippet demonstrates how to enhance an Express.js application's security by setting various HTTP response headers using the `helmet` middleware. `helmet` is a collection of middleware that automatically adds critical headers such as HTTP Strict Transport Security (HSTS), X-Frame-Options, X-Content-Type-Options, and others. These headers help mitigate common web vulnerabilities like clickjacking, MIME-sniffing attacks, and ensure encrypted connections, significantly improving overall application security with minimal configuration.