Web Security Headers Every Developer Should Set
Web Security Headers Every Developer Should Set
Security headers are HTTP response headers that protect your users from common attacks. They're easy to implement and dramatically improve your security posture.
Essential Headers
Content-Security-Policy (CSP)
Controls what resources the browser can load. The most powerful security header:
Content-Security-Policy: default-src 'self'; script-src 'self' https://cdn.example.com; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self'
Start with Content-Security-Policy-Report-Only to test without blocking.
Strict-Transport-Security (HSTS)
Forces HTTPS for all future requests:
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
X-Content-Type-Options
Prevents MIME type sniffing:
X-Content-Type-Options: nosniff
X-Frame-Options
Prevents clickjacking by controlling iframe embedding:
X-Frame-Options: DENY
Or use CSP's frame-ancestors: Content-Security-Policy: frame-ancestors 'none'
Referrer-Policy
Controls how much referrer information is sent:
Referrer-Policy: strict-origin-when-cross-origin
Permissions-Policy
Controls browser feature access:
Permissions-Policy: camera=(), microphone=(), geolocation=(), payment=()
Implementation
Next.js
// next.config.js
const securityHeaders = [
{ key: "X-Content-Type-Options", value: "nosniff" },
{ key: "X-Frame-Options", value: "DENY" },
{ key: "Referrer-Policy", value: "strict-origin-when-cross-origin" },
{ key: "Strict-Transport-Security", value: "max-age=31536000; includeSubDomains" },
];
module.exports = {
async headers() {
return [{ source: "/(.*)", headers: securityHeaders }];
},
};
Nginx
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "DENY" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
Testing
Use securityheaders.com to scan your site and get a grade. Check our SSL Certificate Checker for TLS configuration.
Conclusion
Security headers take minutes to implement and protect against XSS, clickjacking, MIME sniffing, and downgrade attacks. Set them in your web server or framework config and test with a scanner.