2 Hours
16. Security Headers & HTTPS
Security Headers
HTTP security headers provide an additional layer of protection against common attacks. HTTPS encrypts all communication between client and server. This module covers configuring security headers, enforcing HTTPS, and TLS best practices.
Essential Security Headers
These headers protect against XSS, clickjacking, MIME sniffing, and other attacks.
Text
Header Purpose ───────────────────────────────────────────────────────────────────── Content-Security-Policy Controls which resources can load Strict-Transport-Security Enforces HTTPS connections X-Frame-Options Prevents clickjacking (iframe embedding) X-Content-Type-Options Prevents MIME type sniffing Referrer-Policy Controls referrer information sent Permissions-Policy Controls browser features (camera, mic)
Quick win: Use the
helmet package in Node.js to set all these headers automatically.Setting Security Headers (Node.js)
JavaScript
const helmet = require('helmet'); // Helmet sets 12 security headers automatically app.use(helmet()); // Custom configuration for stricter CSP app.use(helmet({ contentSecurityPolicy: { directives: { defaultSrc: ["'self'"], scriptSrc: ["'self'", "'unsafe-inline'", "https://trusted-cdn.com"], styleSrc: ["'self'", "'unsafe-inline'"], imgSrc: ["'self'", "data:", "https://images.unsplash.com"], connectSrc: ["'self'", "https://api.myapp.com"], fontSrc: ["'self'"], objectSrc: ["'none'"], frameAncestors: ["'none'"], formAction: ["'self'"] } }, hsts: { maxAge: 31536000, // 1 year includeSubDomains: true, preload: true }, frameguard: { action: 'deny' }, noSniff: true, referrerPolicy: { policy: 'strict-origin-when-cross-origin' } }));
Manual Security Headers
If you can't use Helmet, set headers manually.
JavaScript
app.use((req, res, next) => {
// Prevent XSS on older browsers
res.setHeader('X-XSS-Protection', '1; mode=block');
// Prevent MIME type sniffing
res.setHeader('X-Content-Type-Options', 'nosniff');
// Prevent clickjacking
res.setHeader('X-Frame-Options', 'DENY');
// Control referrer information
res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');
// Restrict browser features
res.setHeader('Permissions-Policy', 'geolocation=(), microphone=(), camera=()');
// Enforce HTTPS for 1 year
res.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains; preload');
next();
});
Enforcing HTTPS
Always redirect HTTP to HTTPS in production.
JavaScript
// Redirect HTTP to HTTPS app.use((req, res, next) => { if (req.headers['x-forwarded-proto'] !== 'https' && process.env.NODE_ENV === 'production') { return res.redirect(`https://${req.headers.host}${req.url}`); } next(); }); // Or use the express-https-redirect package const httpsRedirect = require('express-https-redirect'); app.use(httpsRedirect());
Never run production without HTTPS! Without HTTPS, all data including passwords and tokens are sent in plain text.
HTTP Strict Transport Security (HSTS)
HSTS tells browsers to always use HTTPS for your domain, even if the user types http://.
Text
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload max-age: How long to remember (1 year) includeSubDomains: Apply to all subdomains preload: Submit to browser preload lists Benefits: - Prevents SSL stripping attacks - Users always get secure connection - Eliminates insecure redirects
HSTS Preload: Submit your domain to hstspreload.org to have browsers always use HTTPS, even on first visit.
Content Security Policy (CSP) Explained
CSP is your most powerful defense against XSS. It tells the browser what sources are allowed.
Text
CSP Directives: default-src 'self' → Only load resources from same origin script-src 'self' cdn.com → Scripts from same origin or cdn.com style-src 'self' 'unsafe-inline' → Styles from same origin or inline img-src 'self' data: https:// → Images from same origin, data URIs, or HTTPS connect-src 'self' api.com → XHR/fetch to same origin or api.com font-src 'self' → Fonts from same origin frame-ancestors 'none' → Cannot be embedded in iframes form-action 'self' → Forms submit to same origin
Start with report-only mode: Use Content-Security-Policy-Report-Only first to test without breaking your site.
Knowledge Check
Ready to test your understanding of 16. Security Headers & HTTPS?