JAVASCRIPT
Enhance Web Security with HTTP Headers
Protect your Node.js Express application from common web vulnerabilities by implementing essential HTTP security headers using the Helmet middleware.
const express = require('express');
const helmet = require('helmet');
const app = express();
// Use Helmet to set various security-related HTTP headers
app.use(helmet());
// Optionally, customize specific headers
app.use(helmet.contentSecurityPolicy({
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", "'unsafe-inline'"],
imgSrc: ["'self'", "data:"],
styleSrc: ["'self'", "'unsafe-inline'"],
},
}));
// X-Frame-Options can be set explicitly if needed (Helmet sets it by default)
app.use(helmet.frameguard({ action: 'deny' }));
// X-Powered-By is often removed by Helmet by default, but explicitly disable it if not using Helmet
app.disable('x-powered-by');
app.get('/', (req, res) => {
res.send('Hello Secure World!');
});
app.listen(3000, () => console.log('Server running on port 3000'));
How it works: This code snippet shows how to implement crucial HTTP security headers in an Express application using the `helmet` middleware. `helmet` is a collection of 14 smaller middleware functions that set various security-related HTTP headers. These headers help protect against common attacks like Cross-Site Scripting (XSS), clickjacking (X-Frame-Options), and MIME-type sniffing (X-Content-Type-Options). The example also shows how to customize a Content Security Policy (CSP) to restrict sources for content, further mitigating XSS and data injection attacks. Disabling the `X-Powered-By` header prevents attackers from easily identifying the server technology.