JAVASCRIPT
Add Essential HTTP Security Headers to Express.js
Enhance your Express.js application's security by adding critical HTTP headers like HSTS, X-Frame-Options, and X-Content-Type-Options to mitigate common web vulnerabilities.
const express = require('express');
const helmet = require('helmet'); // Recommended for a complete set of security headers
const app = express();
const port = 3000;
// --- Recommended: Use Helmet middleware for a broad set of security headers ---
// Helmet is a collection of 14 smaller middleware functions that set security-related HTTP headers
app.use(helmet());
// --- Manual configuration for specific headers if not using Helmet or for custom overrides ---
app.use((req, res, next) => {
// HTTP Strict Transport Security (HSTS)
// Forces clients to use HTTPS for a specified duration
res.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains; preload');
// X-Frame-Options
// Prevents clickjacking by restricting who can embed your site in a frame
res.setHeader('X-Frame-Options', 'DENY'); // Other options: 'SAMEORIGIN'
// X-Content-Type-Options
// Prevents MIME-sniffing vulnerabilities
res.setHeader('X-Content-Type-Options', 'nosniff');
// X-XSS-Protection
// Enables the XSS filter built into most modern web browsers
res.setHeader('X-XSS-Protection', '1; mode=block');
// Referrer-Policy
// Controls how much referrer information is sent with requests
res.setHeader('Referrer-Policy', 'no-referrer-when-downgrade');
// Optionally, you might want to remove the X-Powered-By header
// which can expose information about your server-side technology.
res.removeHeader('X-Powered-By');
next();
});
app.get('/', (req, res) => {
res.send('Hello Secure World!');
});
app.listen(port, () => {
console.log(`Server listening at http://localhost:${port}`);
});
How it works: This Node.js Express snippet shows how to add crucial HTTP security headers to your web application. It primarily recommends using the `helmet` middleware, which automatically sets several important headers to protect against common vulnerabilities like XSS, clickjacking, and MIME-sniffing. Additionally, it demonstrates how to manually set specific headers like `Strict-Transport-Security` (HSTS) for enforcing HTTPS, `X-Frame-Options` to prevent content from being embedded in iframes, `X-Content-Type-Options` to prevent browser MIME type guessing, and `X-XSS-Protection` to enable browser-based XSS filters. These headers significantly harden your application's client-side security posture.