Security headers are your first line of defense against common web attacks. They're easy to implement and significantly improve your application's security posture.
Essential Security Headers#
Content-Security-Policy (CSP)#
CSP Directives Explained#
Directive Purpose
─────────────────────────────────────────────────────
default-src Fallback for other directives
script-src JavaScript sources
style-src CSS sources
img-src Image sources
font-src Font file sources
connect-src XHR, WebSocket, fetch destinations
frame-src iframe sources
frame-ancestors Who can embed this page
base-uri Restrict <base> element
form-action Form submission destinations
upgrade-insecure Upgrade HTTP to HTTPS
Strict CSP with Nonces#
X-Content-Type-Options#
X-Frame-Options#
Referrer-Policy#
Permissions-Policy#
HTTPS Configuration#
HSTS (HTTP Strict Transport Security)#
Redirect HTTP to HTTPS#
TLS Configuration#
Secure Cookies#
Cookie Attributes#
Attribute Purpose
────────────────────────────────────────────────────
Secure Only sent over HTTPS
HttpOnly Not accessible via JavaScript
SameSite CSRF protection
- Strict Only same-site requests
- Lax GET from external sites OK
- None Cross-site (requires Secure)
Domain Which domains receive cookie
Path URL path scope
Max-Age Lifetime in seconds
Expires Absolute expiration date
Using Helmet.js#
Next.js Configuration#
Testing Security Headers#
Online Tools#
- securityheaders.com - Grade your headers
- observatory.mozilla.org - Mozilla security scanner
- csp-evaluator.withgoogle.com - CSP analysis
Command Line#
Automated Testing#
CSP Reporting#
Conclusion#
Security headers are low-effort, high-impact protections. Start with the essentials (HSTS, CSP, X-Content-Type-Options), then add more as needed. Use tools like Helmet.js to simplify implementation.
Test your headers regularly, monitor CSP reports, and keep your TLS configuration updated. Security is an ongoing process, not a one-time setup.