JAVASCRIPT
Configure Essential Security HTTP Headers in Node.js
Enhance web application security by configuring crucial HTTP headers like Content Security Policy (CSP), HSTS, and X-Frame-Options using the 'helmet' middleware in an Express.js app.
const express = require('express');
const helmet = require('helmet');
const app = express();
// Use Helmet to set various security headers
app.use(helmet());
// You can customize specific headers if needed
app.use(helmet.contentSecurityPolicy({
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", "'unsafe-inline'"], // Be cautious with 'unsafe-inline' in production
styleSrc: ["'self'", "https://fonts.googleapis.com"],
imgSrc: ["'self'", "data:"],
connectSrc: ["'self'"],
fontSrc: ["'self'", "https://fonts.gstatic.com"],
}
}));
app.use(helmet.hsts({
maxAge: 31536000, // 1 year in seconds
includeSubDomains: true,
preload: true
}));
app.get('/', (req, res) => {
res.send('Hello Secure World!');
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
How it works: This snippet shows how to integrate `helmet` into an Express.js application to automatically set a collection of security-focused HTTP headers. These headers help protect against common web vulnerabilities like XSS, clickjacking, and insecure connections. It also demonstrates how to customize headers like Content Security Policy (CSP) to define allowed content sources and HTTP Strict Transport Security (HSTS) to enforce HTTPS, providing fine-grained control over security policies.