JAVASCRIPT
Enhance Web Security with HTTP Security Headers
Improve your Node.js application's security posture by setting essential HTTP headers like CSP, HSTS, and X-Frame-Options using the 'helmet' middleware for Express.
// Install: npm install express helmet
const express = require('express');
const helmet = require('helmet');
const app = express();
const port = 3000;
// Use Helmet to set various security headers
app.use(helmet());
// You can configure specific headers if needed, e.g., CSP
app.use(helmet.contentSecurityPolicy({
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", "'unsafe-inline'"], // Example, consider carefully
styleSrc: ["'self'", "https://fonts.googleapis.com"],
imgSrc: ["'self'", "data:"],
fontSrc: ["'self'", "https://fonts.gstatic.com"],
},
}));
// Basic route
app.get('/', (req, res) => {
res.send(`
<html>
<head>
<title>Helmet Security Headers</title>
<style>body { font-family: sans-serif; }</style>
</head>
<body>
<h1>Web Security with Helmet</h1>
<p>Check your browser's developer tools for security headers (e.g., in the Network tab).</p>
</body>
</html>
`);
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
console.log('Visit http://localhost:3000 and inspect response headers.');
});
How it works: This snippet demonstrates how to easily add crucial HTTP security headers to your Express.js 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 web vulnerabilities like Cross-Site Scripting (XSS), clickjacking, and more. For instance, Content Security Policy (CSP) mitigates XSS by whitelisting trusted content sources, and HSTS (Strict-Transport-Security) forces browsers to only communicate with your site over HTTPS.