JAVASCRIPT
Enhance Express Security with Helmet.js HTTP Headers
Enhance Node.js Express security by implementing essential HTTP headers with Helmet.js to mitigate common web vulnerabilities like XSS and clickjacking.
const express = require('express');
const helmet = require('helmet'); // Import Helmet.js
const app = express();
const port = 3000;
// Use Helmet to set various HTTP headers for security
// Helmet is a collection of 15 smaller middleware functions
// that set security-related HTTP headers.
app.use(helmet());
// You can customize individual headers if needed, for example:
// Disabling CSP to show how to specifically override a default
// app.use(helmet.contentSecurityPolicy({
// directives: {
// defaultSrc: ["'self'"],
// scriptSrc: ["'self'", "trusted-cdn.com"],
// imgSrc: ["'self'", "data:"],
// }
// }));
// Explicitly set X-Frame-Options to DENY (Helmet's default is SAMEORIGIN)
// You'd typically only do this if you need a specific value that differs from Helmet's default
// For X-Frame-Options, Helmet by default uses 'SAMEORIGIN' via `frameguard()`.
// If you need 'DENY', you'd use:
app.use(helmet.frameguard({ action: 'deny' }));
// This sets X-Permitted-Cross-Domain-Policies to 'none'
app.use(helmet.permittedCrossDomainPolicies());
// Simple route
app.get('/', (req, res) => {
res.send('Hello Secure World!');
});
// Start the server
app.listen(port, () => {
console.log(`Secure Express app listening at http://localhost:${port}`);
console.log('Check your browser\'s developer tools (Network tab) for security headers.');
});
// To run this:
// 1. npm init -y
// 2. npm install express helmet
// 3. node your_file_name.js
// Then access http://localhost:3000 in your browser and inspect network headers.
How it works: This Node.js Express snippet demonstrates how to easily implement a comprehensive set of HTTP security headers using the `helmet` middleware. Helmet.js helps protect your application from common web vulnerabilities by automatically setting headers like `X-Content-Type-Options`, `X-Frame-Options`, `Strict-Transport-Security` (HSTS), `X-XSS-Protection`, `Content-Security-Policy`, and others. These headers mitigate risks such as Cross-Site Scripting (XSS), clickjacking, MIME-type sniffing, and insecure connections, significantly enhancing the overall security posture of your web application with minimal effort. You can also customize individual headers as needed.