What Are Security Headers?
HTTP security headers are instructions sent from your web server to the browser with every response. They cost almost nothing to implement and defend against a range of common attacks including cross-site scripting, clickjacking, and man-in-the-middle attacks.
Content-Security-Policy (CSP)
CSP is the most powerful — and most complex — security header. It tells the browser which sources of scripts, styles, images, and other resources are allowed to load.
Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-abc123'; object-src 'none'
What it prevents: Cross-site scripting (XSS). If an attacker injects a tag into your page, CSP prevents it from executing because the script is not from an approved source.
Tip: Start with Content-Security-Policy-Report-Only to collect violations without breaking anything, then tighten the policy.
Strict-Transport-Security (HSTS)
HSTS tells browsers to only ever connect to your site over HTTPS — even if the user types http:// in the address bar.
Strict-Transport-Security: max-age=63072000; includeSubDomains; preload
What it prevents: SSL stripping and man-in-the-middle downgrade attacks. An attacker on the same network cannot intercept traffic by downgrading HTTPS to HTTP.
X-Frame-Options
This header prevents your pages from being embedded in elements on other sites.
X-Frame-Options: DENY
What it prevents: Clickjacking — where an attacker overlays your page inside an invisible iframe to trick users into clicking something.
Note: The modern equivalent is frame-ancestors in CSP, but X-Frame-Options has much wider browser support.
X-Content-Type-Options
Prevents browsers from "sniffing" the MIME type of a response.
X-Content-Type-Options: nosniff
What it prevents: MIME confusion attacks where a plain-text file is interpreted as JavaScript.
Referrer-Policy
Controls how much of the URL is sent in the Referer header when users navigate away from your site.
Referrer-Policy: strict-origin-when-cross-origin
Why it matters: Without this, a URL containing a password-reset token or session ID could be leaked to third-party analytics providers.
Permissions-Policy
Restricts which browser features (camera, microphone, geolocation) can be used on the page.
Permissions-Policy: camera=(), microphone=(), geolocation=()
What it prevents: Malicious third-party scripts quietly accessing device sensors.
Quick Audit
Visit securityheaders.com and enter your domain. It will score your current headers and give specific recommendations in under a minute.
Implementation in Next.js
In next.config.js:
const securityHeaders = [
{ key: 'X-Content-Type-Options', value: 'nosniff' },
{ key: 'X-Frame-Options', value: 'DENY' },
{ key: 'Strict-Transport-Security', value: 'max-age=63072000; includeSubDomains; preload' },
{ key: 'Referrer-Policy', value: 'strict-origin-when-cross-origin' },
];
module.exports = {
async headers() {
return [{ source: '/(.*)', headers: securityHeaders }];
},
};